JPA CascadeType.PERSIST如何工作?

时间:2012-10-16 05:16:26

标签: java jpa

在我的示例中,EmployeeOneToOne的{​​{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();
}

1 个答案:

答案 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);
}