我知道已经有一大堆关于这个错误的问题,但似乎没有一个解决方案适用。
我想要create or update父实体"p“和always delete old and create new子实体"c”。
在服务上,在具有以下功能的异步控制器下:
@Async("SomeExecutor")
@Transactional(propagation = Propagation.REQUIRES_NEW)我正在做以下工作:
private SessionFactory sessionFactory;
Session session = this.sessionFactory.getCurrentSession();
for (int i = 0; i < dtoListOfParents.size(); i++) {
ParentEntity p = null;
if(peKeyMap.contains(paKey)){ //just a map with the already existing ParentEntities that I fetch beforehand.
p = peKeyMap.get(paKey);
} else {
p = new ParentEntity();
}
p.setSomeProperty(v1);
p.setSomeOtherProperty(v2);
if(p.getId()==null){
p = (ParentEntity) session.merge(p);
} else {
p.getC.clear();
}
session.flush(); //to get parent id for on create or delete the children on edit.
p.setC(dtoListOfCs, p);
if (i % 50 == 0) {
session.flush(); // Here is where I am getting the error.
session.clear();
}
}Hibernate正在“抱怨”以下几点:
org.hibernate.HibernateException: A collection with cascade="all-delete-orphan"
was no longer referenced by the owning entity instance: ...model.ParentEntity.children子实体:
@Entity
@Table(name = "children")
@DynamicInsert
@DynamicUpdate
public class Children implements Serializable {
private static final long serialVersionUID = 1L;
private ChildrenPK pk;
private ParentEntity parentEntity;
private SecondaryEntity secondaryEntity;
@EmbeddedId
public ChildrenPK getPk() {
return pk;
}
public void setPk(ChildrenPK pk) {
this.pk = pk;
}
public Children() {
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="parent_entity_id", nullable=false, insertable=true, updatable=false)
@MapsId("parentEntityId")
public ParentEntity getParentEntity() {
return this.parentEntity;
}ParentEntity端的关联:
@OneToMany(mappedBy = "parentEntity", cascade = { CascadeType.ALL }, orphanRemoval = true, fetch = FetchType.LAZY)
public List<Children> getChildren() {
return children;
}发布于 2020-10-09 02:03:15
你的代码有点...这很奇怪,但有一句话:
p.setC(dtoListOfCs, p);是否用新的集合覆盖Parent.children?
当使用@OneToMany(orphanRemoval = true)注释映射时,当您使用新的集合覆盖托管实体的集合属性时,Hibernate不喜欢它。如果需要,您需要使用原始列表,添加/删除子项,并清除它。
(请注意,从session.merge()返回的Parent实体已经有一个由Hibernate创建的空集合,即使它在合并之前是null。你应该用那个)
https://stackoverflow.com/questions/64267757
复制相似问题