2014-04-22 35 views
1

我有三個實體。第一個是公司實體(見下文)。如何解決Hibernate中的級聯刪除?

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

我覺得親blem在級聯操作中,但我不確定。有人可以說我該如何解決它?

回答

2

問題出在Employee - HistoryRecord的關係。 HistoryRecord上的員工財產不可空。如果您希望在員工被刪除時刪除HistoryRecord,則需要將級聯屬性添加到Employee的historyRecords的@OneToMany(mappedBy =「employee」)。

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

的ENDDM產生

ALTER TABLE "public"."project_group" ADD CONSTRAINT "mandant" FOREIGN KEY (mandant_id) REFERENCES "mandant" ("mandant_id") ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED; 

數據庫和

@OneToMany(cascade = CascadeType.REMOVE) 
在Java中

enter image description here

0

更新在公司類的關係映射缺少級聯。

@OneToMany(mappedBy = "company", cascade = CascadeType.ALL) 
private List<HistoryRecord> historyRecords;