Hibernate JPA, one-on-one saving child class

I have a one-to-one relationship using PrimaryKeyJoinColumn annotated on the parent side. And now I want to save the child object by itself.

For example, I have Employee and EmpInfo as a child, I need to save EmpInfo (of course, after setting the parent id property for it). However, when such a layout is used, I get the exception below ...

 org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist 

Any ideas why sleep mode doesn't allow this? To be more clear, the code I have is below ...

ParentEntity:

 public class Employee { private Long id; private String name; private EmployeeInfo info; private Integer enumId; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } @Column(name="EMP_NAME") public String getName() { return name; } @PrimaryKeyJoinColumn @OneToOne(cascade = CascadeType.REMOVE) public EmployeeInfo getInfo() { return info; } } 

ChildEntity:

 @Table(name="EMP_INFO") @Entity public class EmployeeInfo { private Long id; private String email; @Column(name="EMPLOYEE_EMAIL") public String getEmail() { return email; } @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "emp_id", nullable = false) public Long getId() { return id; } } 

How am I trying to save it ...

 Employee emp = new Employee(); emp.setEnumId(SimpleEnum.COMPLETE); emp.setName("Shreyas"); EmployeeInfo info = new EmployeeInfo(); info.setEmail(" Sh@gmail "); concreteDAO.save(emp); // This uses the JPATemplate provided by Spring JpaDaoSupport info.setId(emp.getId()); concreteDAO.saveEmpInfo(info); 

Any pointers would be much appreciated, how can I try to save a child?

+4
source share
1 answer

The problem is that @Id of EmployeeInfo declared as automatically generated, and therefore you should not set it manually (Hibernate looks at the object passed to persist and assumes that it is already in the database, because the @Id field @Id filled) .

In other words, remove @GeneratedValue on EmployeeInfo if you want to manually install PK.

Note that Hibernate provides support for the OneToOne association using the shared primary key in JPA 1.0 through a custom extension. Cm:

In JPA 2.0, derived identifiers are well supported, and you can annotate the OneToOne and ManyToOne associations using @Id . Cm:

+9
source

All Articles