eclipse
eclipse

Reputation: 3021

JPA removal annotations

So this is my setup:

public class Record {
    //Stuff
}

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

When I delete an object of Class Record I want the Object of Class RecordNotification that contains this Record to be removed as well. There is always 1 Object of type RecordNotification that contains the same Record at most. Record doesn't know RecordNotification. If RecordNotification is removed nothing else happens.

Upvotes: 0

Views: 217

Answers (1)

Tom Anderson
Tom Anderson

Reputation: 47213

You'll have to add a property to Record that points to the relevant RecordNotification. Then you can mark it as cascading deletes. Like this:

@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() {}
}

The generated DDL was:

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;

I have verified that this works: creating a Record and a RecordNotification, committing, then deleting the Record and noting that the RecordNotification goes away.

I used Hibernate 4.1.4.Final. If this doesn't work for you, then i suspect a bug or misbehaviour in EclipseLink.

Upvotes: 3

Related Questions