如何从在两个不同实体上初始化的OneToMany关系中删除对象?

时间:2019-10-02 08:04:01

标签: hibernate jpa one-to-many sql-delete

我在两个实体中声明了List:

//entity: Foo
@OneToMany(fetch = FetchType.EAGER, mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)
@Fetch(FetchMode.SUBSELECT)
private List<BarFoo> barFoos;

//entity: Bar
@OneToMany(fetch = FetchType.EAGER, mappedBy = "bar", cascade = CascadeType.ALL, orphanRemoval = true)
@Fetch(FetchMode.SUBSELECT)
private List<BarFoo> barFoos;

然后我正试图从Bar实体中删除Foo对象,即我需要从相应的List(在Bar和Foo实体中)中删除BarFoo对象。

我已成功删除它,但数据仍未合并。我不知道该怎么办才能解决此问题,所以我想向您寻求帮助。

//id from BarFoo class:
@EmbeddedId
private BarFooId barFooId = new BarFooId ();

//id class:
private Integer barId;
private Integer fooId;

if(!barFoosToDelete.isEmpty()){

    barFoosToDelete.stream()
        .map(BarFoo::getFoo)
        .forEach(foo -> foo.getBarFoos().removeAll(barFoosToDelete.stream()
            .filter(barFoo -> barFoo.getFoo().equals(foo))
            .collect(Collectors.toList())));

    barFoosToDelete.forEach(barFoo -> fooCRUD.merge(barFoo.getFoo()));
    barFoosToDelete.forEach(barFoo -> barFooCRUD.remove(barFoo));

    barFoosToDelete.clear();
}

0 个答案:

没有答案