2013-06-12 113 views
0

所以這是我的設置:JPA去除註釋

public class Record { 
    //Stuff 
} 

public class RecordNotification { 
    @ What Comes Here? 
    private Record record; 
} 

當我刪除類記錄的對象我想要刪除類RecordNotification包含這個記錄物體爲好。總是有一個RecordNotification類型的對象最多包含相同的Record。記錄不知道RecordNotification。如果RecordNotification被移除,則不會發生任何其他事情。

回答

3

您必須添加一個屬性到記錄,指向相關的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; 

我已經驗證了這個工程:創建RecordRecordNotification,提交,然後刪除Record並注意到RecordNotification消失。

我用Hibernate 4.1.4.Final。如果這不適用於您,那麼我懷疑EclipseLink中存在錯誤或不當行爲。

+0

我試過,它給了我一個錯誤:(記錄是類A,recordNotification類B) – eclipse

+2

那麼這是一個恥辱。 –

+0

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