not able to add Data to child tables with OneToMany mapping - java

I am not able add dummy data in child tables while using OneToMany mapping in spring boot. please help me with it
Here is Entity class (only sending join table):
#OneToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
#JoinTable(name = "recipeIngredients",
joinColumns = #JoinColumn(name = "recipe_id"),
inverseJoinColumns = #JoinColumn(name = "ingredient_id"))
private List<RecipeIngredient> recipeIngredientList;
#OneToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
#JoinTable(name = "recipeSteps",
joinColumns = #JoinColumn(name = "recipe_id"),
inverseJoinColumns = #JoinColumn(name = "step_id"))
private List<RecipeSteps> recipeSteps;
public Recipe(Long user_id, String title, String category, String recipeDescription) {
this.user_id = user_id;
this.title = title;
this.category = category;
this.recipeDescription = recipeDescription;
}
//getter setter
here is function for dummy data :
public String recipe(){
Integer i = 1;
Long l = Long.valueOf(i);
Recipe recipe = new Recipe(
l,"Maggie","Veg","2 min Noodles"
);
System.out.println("----------------" + recipe.getRecipeDescription() + " "
+ recipe.getCategory() + " "
+ recipe.getTitle() + " "
+ recipe.getId());
List<RecipeIngredient> list = new ArrayList<>();
list.add(new RecipeIngredient("salt","2kg"));
list.add(new RecipeIngredient("sugar","5kg"));
for (RecipeIngredient iff : list) {
System.out.println("--------------------"+iff.getName() + " " + iff.getIngredientQuantity());
}
List<RecipeSteps> steps = new ArrayList<>();
steps.add(new RecipeSteps("Step 1","chopping","chop the mf vegetables"));
steps.add(new RecipeSteps("Step 2","boiling","boil them rock hard"));
recipe.setRecipeIngredientList(list);
recipe.setRecipeSteps(steps);
recipeRerepository.save(recipe);
return "recipe Here";
}
Here is database table :
and Here error
Hello from AuthTokenFilter JWTnull
----------------2 min Noodles Veg Maggie null
--------------------salt 2kg
--------------------sugar 5kg
Hibernate: insert into recipe_info (category, recipe_description, title, user_id) values (?, ?, ?, ?)
Hibernate: insert into recipe_ingredients (ingredient_quantity, name) values (?, ?)
2021-12-01 18:16:10.692 WARN 375589 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2021-12-01 18:16:10.692 ERROR 375589 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'recipe_id' doesn't have a default value
2021-12-01 18:16:10.786 ERROR 375589 --- [nio-5000-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'recipe_id' doesn't have a default value

Related

Error: attempted to assign id from null one-to-one property [com.dbtest.springboot.db_model.Family.user]

Tell me how to correctly add a collection consisting of information objects to the database (a table, for example, a family) and so that these objects refer to one user in the user table. At the moment, an error occurs, tried different save options, the error continues:
Request json:
[
{
"name":"luda",
"surname":"Petrova",
"phone":"2353636",
"bus":"black"
},
{
"name":"dima",
"surname":"Petrov",
"phone":"23536336",
"bus":"red"
},
{
"name":"ivan",
"surname":"Petrov",
"phone":"2353",
"bus":"blue"
}
]
RestController :
#RequestMapping(value = { "fam/{id}" },method = RequestMethod.POST)
public User addyfam (#PathVariable Long id, #RequestBody List<FamReq> fammreq){
User usr = userRepo.findById(id).get();
var arr = new ArrayList<Family>();
for(FamReq f : fammreq ) {
arr.add(new Family( f.getName(),f.getSurname(),f.getPhone(),f.getBus()));
}
usr.setFamily(arr);
userRepo.save(usr);
return usr;
}
Entity 1 :
#Entity
#Table(name="usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="name")
private String name;
#Column(name="surname")
private String surname;
#OneToOne(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
#JsonManagedReference
private Passport passport;
#OneToMany(
mappedBy = "user",
cascade = {CascadeType.ALL},
orphanRemoval = true
)
private List<Family> family = new ArrayList<>();
/**get/set and constr **/
}
Entity 2:
#Entity
#Table(name="family")
public class Family {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="name")
private String name;
#Column(name="surname")
private String surname;
#Column(name="phone")
private String phone;
#Column(name="bus")
private String bus;
#ManyToOne(
fetch = FetchType.LAZY
)
#MapsId
#NotFound(action = NotFoundAction.IGNORE)
private User user;
/**get/set and constr **/
}
Since the primary key identifier is identical to the foreign key, it is necessary that the family table contains only the secondary key, and the user table contains only its primary key.
UPDATE :
#RequestMapping(value = { "fam/{id}" },method = RequestMethod.POST)
public User addyfam (#PathVariable Long id, #RequestBody List<FamReq>
fammreq){
User us = userRepo.findById(id).get();
var arr = new ArrayList<Family>();
for(FamReq f : fammreq ) {
Family savedFamily = famRepo.save(new Family(f.getName(),f.getSurname(),f.getPhone(),f.getBus()));
arr.add(savedFamily);
Family(f.getName(),f.getSurname(),f.getPhone(),f.getBus()));
}
userRepo.save(arr);
return us;
}
If, in essence, the family indicates this:
#ManyToOne( cascade = CascadeType.ALL,
fetch = FetchType.LAZY
)
#JoinColumn(name="user_id", referencedColumnName = "id")
private User user;
Error:
ERROR: NULL in column "user_id" of relationship "family" violates NOT NULL constraint
Details: The error line contains (sdgsgsgsegf, luda, 2353636, Petrova, null, null)
If you indicate this:
#ManyToOne(
fetch = FetchType.LAZY
)
#MapsId
#NotFound(action = NotFoundAction.IGNORE)
private User user;
then
Error:
Error: attempted to assign id from null one-to-one property [com.dbtest.springboot.db_model.Family.user]
UPDATE:
the controller is currently in use :
#RequestMapping(value = { "fam/{id}" },method = RequestMethod.POST)
public User addyfam (#PathVariable Long id, #RequestBody List<FamReq> fammreq){
User usr = userRepo.findById(id).get();
var arr = new ArrayList<Family>();
for(FamReq f : fammreq ) {
arr.add(new Family( f.getName(),f.getSurname(),f.getPhone(),f.getBus()));
}
usr.setFamily(arr);
userRepo.save(usr);
return usr;
}
Repo:
#Repository
public interface UserRepo extends JpaRepository<User, Long >{
User findByname(String name);
void save(ArrayList<Family> fm);
}
full error :
Hibernate: insert into family (bus, name, phone, surname, user_id) values (?, ?, ?, ?, ?)
Hibernate: insert into family (bus, name, phone, surname, user_id) values (?, ?, ?, ?, ?)
Hibernate: insert into family (bus, name, phone, surname, user_id) values (?, ?, ?, ?, ?)
2021-11-14 23:31:06.693 ERROR 13192 --- [nio-9091-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'id' of bean class [java.util.ArrayList]: Could not find field for property during fallback access!] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'id' of bean class [java.util.ArrayList]: Could not find field for property during fallback access!
at org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper.getPropertyValue(DirectFieldAccessFallbackBeanWrapper.java:58) ~[spring-data-commons-2.5.6.jar:2.5.6]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.getId(JpaMetamodelEntityInformation.java:162) ~[spring-data-jpa-2.5.6.jar:2.5.6]
at org.springframework.data.repository.core.support.AbstractEntityInformation.isNew(AbstractEntityInformation.java:46) ~[spring-data-commons-2.5.6.jar:2.5.6]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.isNew(JpaMetamodelEntityInformation.java:246) ~[spring-data-jpa-2.5.6.jar:2.5.6]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:596) ~[spring-data-jpa-2.5.6.jar:2.5.6]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
The problem here is that you try to make a relation by Id but new Family( f.getName(),f.getSurname(),f.getPhone(),f.getBus()) does not assign any Id to your Family.
Create Family Object and store it into a variable.
Save your Family with the help of .save(familyObject) only then your Family is assigned with an Id.
Save your User with a Family attached to it.
Your controller should look like this:
for (FamReq f : fammreq ) {
Family savedFamily = familyRepo.save(new Family(f.getName(),f.getSurname(),f.getPhone(),f.getBus(), us.getId()));
arr.add(savedFamily);
}
us.setFamily(arr);wq21`
userRepo.save(us);
You also should have a FamilyRepository like so:
#Repository
public interface FamilyRepo extends JpaRepository<Family, Long>{
}
NOTE: Do not forget to create injection of this class in your Controller.
NOTE: Never override the .save() method in the Repositories.
Plus you have to insure that your user is found by id otherwise throw an exception that will be caught by Global Controller Advice. Because if you do not your JPA will try to create a relation while referring to a NULL value.

Column 'id' not found. SpringBoot

i'm trying to execute this query inside the spring boot repository class , but console shows the error ' column id not found ' also the postman shows:
"status": 500,
"error": "Internal Server Error",
"message": "could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query",
QUERY REPOSITORY
#Query(nativeQuery=true, value="SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= :year")
public List<User> findALLUserByyear(#Param("year") String year);
CONTROLLER
#GetMapping(value="/etablissementAlls/{year}")
public EtablissementDto EtabDTOALL(#PathVariable String year) {
EtablissementDto a = new EtablissementDto();
a.setUsers(userRepository.findALLUserByyear(year));
return a;
}
Stack Trace
2021-05-05 11:14:17.600 WARN 5240 --- [nio-8020-exec-2] org.club.config.JwtRequestFilter : JWT Token does not begin with Bearer String
2021-05-05 11:14:17.604 WARN 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S0022
2021-05-05 11:14:17.604 ERROR 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'id' not found.
2021-05-05 11:14:17.606 ERROR 5240 --- [nio-8020-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1080) ~[mysql-connector-java-5.1.46.jar:5.1.46]
NOTE
I tested this query in MYSQL PHPmyAdmin, and it works fine
USER ENTITY
#Entity
#Table(name = "app_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "is_active")
private boolean active;
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
#JoinTable(name = "user_etablissement", joinColumns
= #JoinColumn(name = "user_id",
referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "etablissement_id",
referencedColumnName = "id"))
private List<Etablissement> etablissements;
Clarify few things:
The MYSQL PHPmyAdmin you have queried on and the service you are connecting database to are pointing to the same database server?
Have you checked manually if 'id' column is created in the tables you are querying to?
You should change your query if you have create_time field in User entity
#Query(value="SELECT u from User u where year(u.creatdate_time)=:year")
public List<User> findALLUserByyear(#Param("year") String year);

Hibernate save or update with JoinColumn

I would have a problem with create a new entity, if it have a join column.
Entity:
#
Entity
#Table(name = "projects")
public class Project {
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
#Column(name = "id_project")
private Long id;
#Column(name = "project_name")
private String name;
#JsonInclude(value = Include.NON_NULL)
#Column(name = "project_language")
private String language;
#Temporal(TemporalType.DATE)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
#Column(name = "start_date")
private Date start_date;
#Temporal(TemporalType.DATE)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
#Column(name = "end_date")
private Date end_date;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "id_content_manager")
private User contentManager;
if i send this json:
{
"name": "prova3",
"language": "1",
"start_date": "15-04-2018",
"end_date": "26-04-2018"
}
the result are:
Hibernate: insert into projects (id_content_manager, end_date, project_language, project_name, start_date, id_project) values (?, ?, ?, ?, ?, ?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1452, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`dipp`.`projects`, CONSTRAINT `projects_user_id_user_fk` FOREIGN KEY (`id_project`) REFERENCES `user` (`id_user`) ON DELETE CASCADE ON UPDATE CASCADE)
ERROR: org.hibernate.internal.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
the method for save the entity:
public void newProject(Project project) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = null;
tx = session.beginTransaction();
if(session != null) {
try {
session.save(project);
tx.commit();
session.close();
}catch(Exception ex) {
session.close();
}
}
}
Someone could help me to solve?
I would need to understand how to pass the parameter "contentManager" as optional in order to pass only the id and then through a find function to retrieve everything and pass it to contentManager
Edit:
The controller:
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json" , produces = "application/json")
public #ResponseBody ResponseEntity<BaseModel> newProject( #RequestHeader(value="Authorization") String token, #RequestBody Project project, Locale locale) throws ParseException{
if(!SecurityUtil.validateToken(token)) {
return new ResponseEntity<BaseModel>(new BaseModel("error", MessageHandler.returnMessage("invalid_token", locale)), HttpStatus.UNAUTHORIZED);
}
User contentManager = new User();
logger.info(project.getContentManager().getId().toString());
if(project.getContentManager().getId() != null) {
logger.info("have id");
contentManager = userDao.find(project.getContentManager().getId());
}
project.setContentManager(contentManager);
projectDao.newProject(project);
return new ResponseEntity<BaseModel>(new BaseModel("ok", project.getId()), HttpStatus.OK);
}
The problem is with the foreign key projects_user_id_user_fk remove "ON UPDATE CASCADE" and set "ON UPDATE NO ACTION", because when you insert the id it try to update user table and you probably try to save project with empty user.
This is not an answer. Below is the way I have done, this might help you. Before using it I initialize it and set then set it to use in the parent entity.
Icon icon = new Icon();
icon.setIconPath(MiscUtils.getUserIconPath(user));
icon.setUser(user);
user.setIcon(icon);

java.lang.UnsupportedOperationException: Unrecognized property type: org.hibernate.type.BagType

I am trying to run following hql but getting Caused by: java.lang.UnsupportedOperationException: Unrecognized property type: org.hibernate.type.BagType(org.model.Test.groups) error.
Query query = session.createQuery("from Test t " +
" JOIN FETCH t.groups g " +
" where t.id=:id" +
" and g.value.name= :name ")
.setString("id", id);
.setString("name", name);
List<Test> tList = query.list();
This one also gives the same error;
Query query = session.createQuery("from Test t " +
" JOIN FETCH t.groups g " +
" JOIN FETCH g.value v " +
" where t.id=:id" +
" and v.name= :name ")
.setString("id", id);
.setString("name", name);
#Entity
#Table
public class Test {
...
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Group> groups;
...
}
#Entity
#Table
public class Group {
...
#OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "value")
private Value value;
...
}
#Entity
#Table
public class Value {
...
#Column(name="name", nullable=false)
private String name;
...
}
If i just run the following hql, i am getting the column values for all test, group and value tables without any problem.
Query q = session.createQuery("from Test t where t.id= :id")
.setString("id", id);
below is the full error stack trace;
Caused by: java.lang.UnsupportedOperationException: Unrecognized property type: org.hibernate.type.BagType(org.model.Test.groups)
org.hibernate.ogm.query.parsing.impl.ParserPropertyHelper.getPropertyType(ParserPropertyHelper.java:104)
org.hibernate.ogm.datastore.mongodb.query.parsing.impl.MongoDBPropertyHelper.getPropertyType(MongoDBPropertyHelper.java:48)
org.hibernate.ogm.query.parsing.impl.ParserPropertyHelper.convertToPropertyType(ParserPropertyHelper.java:48)
org.hibernate.hql.ast.spi.SingleEntityQueryRendererDelegate.parameterValue(SingleEntityQueryRendererDelegate.java:465)
org.hibernate.hql.ast.spi.SingleEntityQueryRendererDelegate.addComparisonPredicate(SingleEntityQueryRendererDelegate.java:305)
org.hibernate.hql.ast.spi.SingleEntityQueryRendererDelegate.predicateEquals(SingleEntityQueryRendererDelegate.java:284)
org.hibernate.hql.ast.render.QueryRenderer.predicate(QueryRenderer.java:5238)
org.hibernate.hql.ast.render.QueryRenderer.searchCondition(QueryRenderer.java:4912)
org.hibernate.hql.ast.render.QueryRenderer.searchCondition(QueryRenderer.java:4848)
org.hibernate.hql.ast.render.QueryRenderer.whereClause(QueryRenderer.java:2376)
org.hibernate.hql.ast.render.QueryRenderer.querySpec(QueryRenderer.java:2229)
org.hibernate.hql.ast.render.QueryRenderer.queryExpression(QueryRenderer.java:2132)
org.hibernate.hql.ast.render.QueryRenderer.queryStatement(QueryRenderer.java:1771)
org.hibernate.hql.ast.render.QueryRenderer.queryStatementSet(QueryRenderer.java:1684)
org.hibernate.hql.ast.render.QueryRenderer.statement(QueryRenderer.java:680)
org.hibernate.hql.ast.spi.QueryRendererProcessor.process(QueryRendererProcessor.java:51)
org.hibernate.hql.QueryParser.parseQuery(QueryParser.java:82)
org.hibernate.ogm.datastore.mongodb.query.parsing.impl.MongoDBBasedQueryParserService.parseQuery(MongoDBBasedQueryParserService.java:40)
org.hibernate.ogm.query.impl.OgmQueryTranslator.getQuery(OgmQueryTranslator.java:169)
org.hibernate.ogm.query.impl.OgmQueryTranslator.getLoader(OgmQueryTranslator.java:134)
org.hibernate.ogm.query.impl.OgmQueryTranslator.list(OgmQueryTranslator.java:128)
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
Hibernate OGM does not currently support JP-QL queries with JOIN on *-to-many associations: https://docs.jboss.org/hibernate/stable/ogm/reference/en-US/html_single/#_using_jp_ql
Cannot say if this is the cause of your specific error especially cause there is only partial code from entites. But check this (because it complains about Group)
You seem to be after birectional mapping between Test<>Group, there is #OneToMany annotation and List<Group> groups on Test.
How is Group mapped to Test? There is no mappedBy attribute or similar.
You should have something like:
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="test")
private List<Group> groups;
on Test side. On Group side then you should hava a field like:
#ManyToOne
private Test test;
Maybe you have but not in the provided snippet.

Why cannot join 3rd table using JPA TopLink annotation?

I have simple 3 tables:
Users
-id
-name
Addresses
-id
-user_id //FK
-location
Phone
-id
-number
-address_id //FK
Users can have many Addresses
Addresses can have many Phone
Thus, annotations applied to each entity class would look like:
Users
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Addresses> addresses;
Addresses
#ManyToOne()
#JoinColumn(name = "user_id")
private Users user;
#OneToMany(mappedBy = "address")
private List<Phone> phone;
Phone
#ManyToOne()
#JoinColumn(name = "address_id")
private Addresses address;
The annotation above should create relationship:
users (1) ----- (n) addresses (1) ------ (n) phone
Then I created some test data in MySQL and tried to run test to see if query result that returns "users" would include reference to addresses and phone.
I've tried with 2 table only using users and addresses and got result ok.
Now that I added "phone" table which is 3rd table then I'm getting error shown below.
Is this really right way to join 3 or more tables?
Test code
try {
//get entity manager
String WEB_PU = "NoJSFPU";
EntityManagerFactory factory = Persistence.createEntityManagerFactory(WEB_PU);
EntityManager em = factory.createEntityManager();
//run query
List<Users> usersList = em.createQuery("SELECT u FROM Users u").getResultList();
//loop to print out each result
for(Users item : usersList) {
//display user info
System.out.println(item.getId() + " " + item.getFirstname());
List<Addresses> addrs = item.getAddresses();
for(Addresses ad : addrs) {
//display address info
System.out.println("Address:::" + ad.getLocation());
List<Phone> pho = ad.getPhone();
for(Phone p : pho) {
//display phone info
System.out.println("phone#" + p.getNumber());
}
}//end inner for
}//end outer for
System.out.println("==========================");
}
catch(Exception e) {
System.out.println("seriously wtf: " + e.toString());
System.exit(1);
}
Error
Exception Description: predeploy for PersistenceUnit [NoJSFPU] failed.
Internal Exception: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: [class local.test.session.Addresses] uses a non-entity [class local.test.session.Phone] as target entity in the relationship attribute [private java.util.List local.test.session.Addresses.phone].
I figured out. Had to specify by using #JoinTable annotation.
Now If I run the test code, data from all 3 tables can be obtained :D
Addresses
#ManyToOne
#JoinTable(name = "Addresses", joinColumns = {#JoinColumn(name="user_id",
referencedColumnName = "user_id") } )
private Users user;
Phone
#ManyToOne
#JoinTable(name = "Phone", joinColumns = {#JoinColumn(name="address_id",
referencedColumnName = "address_id") } )
private Addresses address;

Categories