gpt4 book ai didi

java - 如何解决Hibernate中的级联删除问题?

转载 作者:行者123 更新时间:2023-11-30 03:55:49 26 4
gpt4 key购买 nike

我有三个实体。第一个是公司实体(见下文)。

@Entity
public class Company {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Column
private String name;

@JoinColumn(name = "company_id")
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Employee> employees;

@OneToMany(mappedBy = "company")
private List<HistoryRecord> historyRecords;

第二个是员工

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;

@Column
String name;

@ManyToOne
@JoinColumn(name = "company_id", nullable = true)
private Company company;

@OneToMany(mappedBy = "employee")
private List<HistoryRecord> historyRecords;

这是我的 HistoryRecord 类

@Entity
public class HistoryRecord {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;

@ManyToOne
@JoinColumn(name = "company_id")
Employee employee;

@ManyToOne
@JoinColumn(name = "employee_id")
Company company;

@Column(name = "hire_date")
Date hireDate;

@Column(name = "resign_date")
Date resignDate;

当我尝试对员工执行删除操作时,出现此错误

HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [delete from employee where id=?]; constraint [&quot;CONSTRAINT_12: PUBLIC.HISTORY_RECORD FOREIGN KEY(EMPLOYEE_ID) REFERENCES PUBLIC.EMPLOYEE(ID) 

我认为问题出在级联操作中,但我不确定。有人可以告诉我如何修复它吗?

最佳答案

问题是由于 Employee -- HistoryRecord 的关系引起的。 HistoryRecord 上的员工属性不可为空。如果您希望在删除员工时删除 HistoryRecord,则需要为 Employee 上的 HistoryRecords 添加级联属性 @OneToMany(mappedBy = "employee")。

@OneToMany(mappedBy = "employee",cascade = CascadeType.REMOVE)

关于java - 如何解决Hibernate中的级联删除问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23224829/

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