gpt4 book ai didi

java - @OneToMany 中不必要的更新

转载 作者:行者123 更新时间:2023-12-01 11:09:51 25 4
gpt4 key购买 nike

我的模型对象如下

Employee.java
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@SequenceGenerator(name = "emp_seq", sequenceName = "seq_employee")
@GeneratedValue(generator = "emp_seq")
@Column(name = "EMPLOYEE_ID")
private Integer employeeId;
@Column(name = "EMPLOYEE_NAME")
private String employeeName;
}

Department.java
@Entity
@Table(name = "DEPARTMENT")
public class Department {
@Id
@Column(name = "DEPARTMENT_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer departmentId;
@Column(name = "DEPARTMENT_NAME")
private String departmentName;
@Column(name = "LOCATION")
private String location;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "DEPARTMENT_ID")
private List<Employee> employees = new ArrayList<>();
}

在保存它时,它会生成两个额外的更新语句。

测试类

    Employee e1 = new Employee();
e1.setEmployeeName("Employee-1");

Employee e2 = new Employee();
e2.setEmployeeName("Employee-2");

Department d = new Department();
d.setDepartmentName("Test");
d.setLocation("Test");

d.getEmployees().add(e1);
d.getEmployees().add(e2);
em.getTransaction().begin();
em.persist(d);
em.getTransaction().commit();

提交后会生成以下语句...

Hibernate: insert into DEPARTMENT (DEPARTMENT_NAME, LOCATION, DEPARTMENT_ID) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMPLOYEE_NAME, EMPLOYEE_ID) values (?, ?)
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?
**Hibernate: update EMPLOYEE set DEPARTMENT_ID=? where EMPLOYEE_ID=?

我的问题是为什么需要 2 个额外的更新(用 * 标记)语句?

最佳答案

这是 Hibernate 正常执行操作的顺序。看看这个

https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29

根据此文档:

Execute all SQL (and second-level cache updates) in a special order so that foreign-key constraints cannot be violated:

关于java - @OneToMany 中不必要的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498753/

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