给定以下代码
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;
}
保存的类(class)有 2 条评论。
如果我尝试从类(class)中删除一条评论。
course.getReviews().remove(0);
Hibernate 在查询之后触发。
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]
请注意,它首先删除所有关系,然后插入剩余的关系。为什么会有这种行为?为什么不能更具体一些,只删除存储关系的那条记录。
最佳答案
不确定这是由于包语义(因为您使用 List
而不是 Set
进行审查)还是因为 Hibernate 有时会进行所谓的“集合再创造” .尝试使用 Set
。
关于java - 单向@OnetoMany 映射删除所有关系并重新添加剩余关系而不是删除特定关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64363313/