在我的示例中,Employee
与OneToOne
的{{1}}关系Department
。
当我坚持多个CascadeType.PERSIST
时,
为什么Employee
会为所有EntityManager
条记录保留一条Department
条记录?
我的期望是,如果我们使用Employee
,当CascadeType.PERSIST
被保留时,将为每个Employee
记录重新创建Department
条记录。
Employee.java
Employee
Department.java
@Entity
public class Employee {
private String id;
private String name;
@OneToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "DEP_ID", referencedColumnName = "ID")
private Department department;
-----
}
Test.java
@Entity
public class Department implements Serializable {
private String id;
private String name;
}
结果:
public void insert() {
em = emf.createEntityManager();
em.getTransaction().begin();
Department department = new Department("Test Department");
for(int i=1; i <= 10; i++) {
Employee e = new Employee("EMP" + i, department);
em.persist(e);
}
em.getTransaction().commit();
em.close();
}
答案 0 :(得分:13)
JPA维护对象标识,不会保留现有对象。
将您的代码更改为正确,
for(int i=1; i <= 10; i++) {
Department department = new Department("Test Department");
Employee e = new Employee("EMP" + i, department);
em.persist(e);
}