@OneToMany relationship issue while saving multiple values in hibernate and spring -



@OneToMany relationship issue while saving multiple values in hibernate and spring -

iam having 2 entities @onetomany bidirectional relationship below:

@entity public class company { @id @generatedvalue(strategy = generationtype.auto) private integer companyid; private string name; @onetomany(cascade = cascadetype.all, fetch = fetchtype.eager, mappedby="company") set<employee> employees = new linkedhashset<>();

employee class

@entity public class employee { @id @generatedvalue(strategy = generationtype.auto) private integer empid; private string name; private string address; private string email; @manytoone @joincolumn(name="companyid") company company;

intially saved 2 employees below:

employee emp= new employee(); emp.setname("john"); emp.setemail("john@gmail.com"); employeerepository.save(emp); employee emp2= new employee(); emp2.setname("smith"); emp2.setemail("smith@gmail.com"); employeerepository.save(emp2);

now want save 1 employee working 2 different companies below:

company company =new company(); company.setname("google"); employee emp = employeerepository.findone(1); company.getemployees().add(emp); emp.setcompany(company); companyrepository.save(company); company company2 =new company(); company2.setname("microsoft"); company2.getemployees().add(emp); emp.setcompany(company2); companyrepository.save(company2);

it updating sec company id employee table. want both companies assigned employee. how can please help.

thanks in advance

the issue here have one-to-many when should many-to-many, viz. employee can work more 1 company , company has many employees.

you can either alter relationship @manytomany (and utilize @jointable if required) or can create entity, say, companyemployee both employee , company have one-to-many-relationship. latter approach preferable can record additional info association e.g. start_date, end-date etc.

@entity @table(name = "company_employees") public class companyemployee { @manytoone private employee employee; @manytoone private company company; private date startdate; private date enddate; }

spring hibernate jpa ejb-3.0

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -