您必須添加一個屬性到記錄,指向相關的RecordNotification。然後,您可以將其標記爲級聯刪除。就像這樣:
@Entity
public class Record {
@Id
private int id;
@OneToOne(mappedBy="record", cascade={CascadeType.REMOVE})
private RecordNotification notification;
public Record(int id) {
this.id = id;
}
protected Record() {}
}
@Entity
public class RecordNotification {
@Id
private int id;
@OneToOne
private Record record;
public RecordNotification(int id, Record record) {
this.id = id;
this.record = record;
}
protected RecordNotification() {}
}
生成的DDL爲:
create table Record (
id integer not null,
primary key (id)
);
create table RecordNotification (
id integer not null,
record_id integer,
primary key (id)
);
alter table RecordNotification
add constraint FKE88313FC6EE389C1
foreign key (record_id)
references Record;
我已經驗證了這個工程:創建Record
和RecordNotification
,提交,然後刪除Record
並注意到RecordNotification
消失。
我用Hibernate 4.1.4.Final。如果這不適用於您,那麼我懷疑EclipseLink中存在錯誤或不當行爲。
我試過,它給了我一個錯誤:(記錄是類A,recordNotification類B) – eclipse
那麼這是一個恥辱。 –
javax.persistence.RollbackException:異常[EclipseLink-4002](Eclipse持久性服務 - 2.1.2.v20101206-r8635):org.eclipse.persistence.exceptions.DatabaseException 內部異常:java.sql.SQLException:違反完整性約束FK_RECORDNOTIFICATION_RECORD_ID表:RECORDNOTIFICATION在語句[DELETE FROM T_RECORD WHERE(ID =?)] 錯誤代碼:-8 電話:DELETE FROM T_RECORD WHERE(?ID =) \t綁定=> [qTBN-UatHhlnlX-XHFrrvzKOPQJ4iCfMCWy__3LxcyM] – eclipse