我正在尝试使用merge从父实体中删除子项(不删除DB中的引用),我所做的是从父项中获取@OneToMany字段的集合,然后从集合中删除,最后我使用合并,这适用于我使用相同的方法但添加而不是删除,实体是:
@Entity
@Table(name="bills")
public class Bill {
@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="bill")
private Set<BillDetail> billDetails = new LinkedHashSet<>();
...
}
@Entity
@Table(name="billDetails")
public class BillDetail {
@ManyToOne()
@JoinColumn(name="bill")
private Bill bill;
...
}
我执行合并的代码是:
Collection<Object> references = (Collection<Object>) PropertyUtils.getSimpleProperty(parentEntity, referenceField);
references.remove(childEntity); // the adding are the same, only i change remove for add here
PropertyUtils.setSimpleProperty(parentEntity, referenceField,references);
requirementCheck.setData(childEntity);
entityManager.getTransaction().begin();
entityManager.merge(parentEntity);
entityManager.getTransaction().commit();
entityManager.close();
所以当我删除时,我没有看到任何更新日志,我缺少什么?我在进行合并的类上使用@Transactional并且我使用了aspectj和Spring AOP(确保没有将AOP和Aspectj应用于同一个方法)我也在使用Hibernate
答案 0 :(得分:0)
该关系由BillDetail实例拥有,因此对该关系的任何更改都需要更改BillDetail,并且合并BillDetail。
它在添加时有效,因为合并能够在关系上级联,因此BillDetail中的更改也会合并。删除引用时,您会切断此引用,阻止级联选项查找您的BillDetail实例,因此您必须在清除其帐单引用后手动调用merge。