1 Reply Latest reply: Jun 22, 2010 4:26 AM by 843833 RSS

    JPA, how to write a service to persist objects in a 1-to-many relationship

      i am using JPA for data persistence. i have two objects that are involved in a one-to-many relationship. for example, i have an object, Company, and Company can have one or more, Employee. i then define a service called, CompanyDao, which has the usual create-read-update-delete (CRUD) operations. my problem is that when i instantiate a new Company with new Employees and call CompanyDao.create(Company), i keep getting an exception.

      Cannot add or update a child row: a foreign key constraint fails (`demo`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`companyId`) REFERENCES `company` (`id`))

      i have an intuition on why this is happening. when i call CompanyDao.create(Company), the newly instantiated Company doesn't yet have an id (its unique identifier). that is why when it tries to insert the Employees of Company, i get this problem. but, my question is, shouldn't JPA take care of all of this for me? shouldn't it know that it is creating a new Company, will have to insert it, will have to retrieve the unique id (generated) and then populate the employee table with this id?

      i was thinking about this problem, and i thought maybe i could insert the company first and then the employees later. however, the problem is, once i insert the company, how do i get its unique id? i cannot query for it any other way (i.e. by name) that will return a unique result.

      if anyone knows of a good, comprehensive tutorial on how to write a service demonstration CRUD operations on objects with one-to-many relationship, please let me know.