gpt4 book ai didi

java - JPA CascadeType.PERSIST 是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 22:56:23 25 4
gpt4 key购买 nike

在我的示例中,EmployeeDepartment 具有CascadeType.PERSISTOneToOne 关系。当我坚持多个 Employee,


为什么 EntityManager 为所有 Employee 记录保留一个 Department 记录?


我的期望是,如果我们使用 CascadeType.PERSIST,当一个 Employee 被持久化时,一个 Department 记录将被重新创建每个 Employee 记录。

员工.java

@Entity
public class Employee {
private String id;
private String name;
@OneToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "DEP_ID", referencedColumnName = "ID")
private Department department;

-----
}

部门.java

@Entity
public class Department implements Serializable {
private String id;
private String name;
}

测试.java

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();
}

结果:

Employee Table          Department Table
================= ==============================
ID Name DEP_ID ID NAME
================= ==============================
1 EMP1 1 1 Test Department
2 EMP2 1
3 EMP3 1
4 EMP4 1
5 EMP5 1
6 EMP6 1
7 EMP7 1
8 EMP8 1
9 EMP9 1
10 EMP10 1

最佳答案

JPA 维护对象标识,不会保留现有对象。

更改您的代码以使其正确,

for(int i=1; i <= 10; i++) {
Department department = new Department("Test Department");
Employee e = new Employee("EMP" + i, department);
em.persist(e);
}

关于java - JPA CascadeType.PERSIST 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com