单向@OnetoMany映射将删除所有关系并重新添加剩余的关系,而不是删除特定的关系 [英] Unidirectional @OnetoMany mapping deletes all relationships and re-adds remaining ones rather than removing the specific one

查看:84
本文介绍了单向@OnetoMany映射将删除所有关系并重新添加剩余的关系,而不是删除特定的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码

public class Course {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Review> reviews = new ArrayList<>();
}

public class Review {
    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String rating;
    private String description;
}

保存的课程有2条评论.

Saved course with 2 reviews.

如果我尝试从课程中删除一条评论.

If I try to remove one review from course.

course.getReviews().remove(0);

休眠触发以下查询.

delete from course_reviews where course_id=? 
binding parameter [1] as [BIGINT] - [1]
insert into course_reviews (course_id, reviews_id) values (?, ?) 
binding parameter [1] as [BIGINT] - [1]
binding parameter [2] as [BIGINT] - [3]

请注意,它将首先删除所有关系,然后插入其余的关系.为什么会这样呢?为什么不能更具体地删除存储关系的那条记录呢?

Notice that it deletes all the relationships first and then inserts the remaining. Why this behavior? Why couldn't it be more specific and delete just that one record storing the relationship.

推荐答案

不确定这是否是由于包语义所致(因为您将 List 而不是 Set 用于评论)或仅仅因为Hibernate有时会进行所谓的收藏娱乐".尝试使用 Set .

Not sure if this is due to bag semantics(because you use a List rather than Set for reviews) or just because Hibernate sometimes does so called "collection recreations". Try using a Set.

这篇关于单向@OnetoMany映射将删除所有关系并重新添加剩余的关系,而不是删除特定的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆