JpaRepository delete child elements

无人久伴 提交于 2019-12-05 22:43:40

Update the A.bList property as follows:

public class A {
    @OneToMany(mappedBy = "a", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    List<B> bList;
}

The orphanRemoval = true annotation attribute will tell the underlying JPA implementation to delete B records which don't have any parent left.

Also, Since the B side manages the association, you should clear its a attribute when breaking the relationship. To make this easier to read and to remove the burden of such implementation details from the caller, you should introduce management methods in A :

public class A {
    public void clearBList() {
        for (B b : bList) {
            b.releaseA();
        }
        bList.clear();
    }
}

public class B {
    void releaseA() {
        this.a = null;
    }
}

You should avoid exposing collections directly and instead return an immutable version of it to prevent clients to the A class of modifying the collection directly without the A class knowing it. A manages the B list, so it should have full control over it!

public class A {
    public List<B> getBList() {
        return Collections.unmodifiableList(bList);
    }
}

Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!