如何避免将已删除的实例传递给与 Set 的一对多关系合并?
How to avoid getting a deleted instance passed to merge on a One To Many relationship with Set?
我在 Hibernate 实体中有这个映射。
A.java
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
Set<B> bs;
B.java
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "A_ID")
A a;
我需要对 A 进行编辑。
所以在用 Spring @Transactional
注释的方法中加载实体之后
A a = entityManager.find(A.class, a.getId);
// set some new values on the instance variables of a.
// take out the set of Bs through a and delete them
for(B b : a.getBs()) {
entityManager.remove(b);
}
// create new objects of B and add them to the below set-
Set<B> bs = new HashSet<>();
a.setBs(bs);
entityManager.merge(a);
以上代码是单一方法的一部分。
我得到 - 已删除的实例已传递给合并。
请提出建议。
您正在 class B
中使用 cascade = CascadeType.ALL
。因此,在执行 entityManager.remove(b)
时,删除操作会级联并删除 a
.
您可以根据需要在 B
中执行类似操作:
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
我在 Hibernate 实体中有这个映射。
A.java
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
Set<B> bs;
B.java
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "A_ID")
A a;
我需要对 A 进行编辑。
所以在用 Spring @Transactional
A a = entityManager.find(A.class, a.getId);
// set some new values on the instance variables of a.
// take out the set of Bs through a and delete them
for(B b : a.getBs()) {
entityManager.remove(b);
}
// create new objects of B and add them to the below set-
Set<B> bs = new HashSet<>();
a.setBs(bs);
entityManager.merge(a);
以上代码是单一方法的一部分。
我得到 - 已删除的实例已传递给合并。 请提出建议。
您正在 class B
中使用 cascade = CascadeType.ALL
。因此,在执行 entityManager.remove(b)
时,删除操作会级联并删除 a
.
您可以根据需要在 B
中执行类似操作:
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST})