문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top