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

@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;


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

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上的employee属性不可为空。如果要在删除员工时删除HistoryRecord,则需要将级联属性添加到员工的HistoryRecords的@OneToMany(mappedBy =“ employee”)。

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

10-04 20:26