1. 程式人生 > >SSH級聯操作報錯:org.hibernate.exception.ConstraintViolationException: Could not execute

SSH級聯操作報錯:org.hibernate.exception.ConstraintViolationException: Could not execute

SSH整合過程中,刪除具有外來鍵的記錄時報錯:

spring4+hibernate4

org.hibernate.exception.ConstraintViolationException: Could not execute 

因為有外來鍵約束,所以報錯。

兩個表的關係為基於外來鍵的雙向1-1關聯

A表主鍵  為 B表的外來鍵

//設定級聯屬性CascadeType為刪除,當刪除A表記錄時,自動刪除B表中具有A外來鍵的記錄
@OneToOne(targetEntity=B.class, mappedBy="B", cascade=CascadeType.REMOVE)
private B  b;
//省略 setter、getter方法

B表對應實體

//設定級聯屬性CascadeType為持久化和重新整理,當刪除B表記錄時,不會刪除A表中對應的記錄,但是更新B表會重新整理A表對應記錄
@OneToOne(targetEntity=A.class,cascade={CascadeType.PERSIST,CascadeType.REFRESH})
//對映a_id外來鍵列,參照a表中的a_id列
@JoinColumn(name="a_id", referencedColumnName="a_id", unique=true)
private A a;