这是我的设置:

public class Record {
    //Stuff
}

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


当我删除类记录的对象时,我也希望删除包含该记录的类RecordNotification的对象。总会有1个RecordNotification类型的对象,最多包含同一条Record。记录不知道RecordNotification。如果RecordNotification被删除,则不会发生其他任何事情。

最佳答案

您必须向Record添加一个属性,该属性指向相关的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中存在错误或不当行为。

10-05 19:17