Question

When manually writing a database schema, it is possible to set a foreign relation cascade to "on delete set null".

I've searched Stackoverflow and google for the answer but I can't find it: how do you get JPA to do the same?

So, when I set a relation with @OneToOne, @OneToMany or @ManyToMany, what CascadeType achieves this, or is it something else I need to do?

As an example, take the objects House and Person. A house can optionally have a person owning it. But suppose the owner dies. The House instance should still exist, but the "owner" field(of type Person) should simply be set to null.

Can this be done automatically with JPA?

Was it helpful?

Solution

One possible way, I think, is using one of entity lifecycle callbacks.

class Person {

    @PreRemove
    protected void makeHouseOnSale() {
        if (owning!= null) {
            owning.owner = null;
        }
    }

    @OneToOne       
    private House owning;
}

class House {
    @OneToOne(
        //optional = true; // default
    )
    private Person owner;
}

When you remove(kill) a Person instance in JTA session, @PreRemove annotated methods are invoked and those two entities commits when the session ends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top