Hibernate 更新一对多关系中的父实体时,如何更新子实体?
我有两个实体称为A和B。模型如下Hibernate 更新一对多关系中的父实体时,如何更新子实体?,hibernate,spring-boot,jpa,one-to-many,Hibernate,Spring Boot,Jpa,One To Many,我有两个实体称为A和B。模型如下 class A { @OneToMany(fetch = FetchType.LAZY,mappedBy = "child", cascade={CascadeType.ALL} , orphanRemoval = true) private Set<B> children = new HashSet<>(); } class B { @ManyToOne(fetch= FetchType.LAZY)
class A {
@OneToMany(fetch = FetchType.LAZY,mappedBy = "child", cascade={CascadeType.ALL} , orphanRemoval = true)
private Set<B> children = new HashSet<>();
}
class B {
@ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name="a_id")
@JsonIgnore
private A child;
}
确保对A中的子项调用remove,并将B中的子项设置为null:
a.getChildren().remove(b);
b.setA(null);
一件很棒的事情就是所谓的便利方法,你可以把它放在你的案例中的一边:
public class A {
// existing code
// Convenience mehtods
public void addChild(B b) {
children.add(b);
b.setA(this);
}
public void removeChild(B b) {
children.remove(b);
b.setA(null);
}
}
这样,您的双向关系总是最新的。当您删除A中的B个孩子时,是否将B中的孩子设置为null?@SimonMartinelli我也这样做了,但什么也没发生。existing.setB(null)这不会从数据库中删除已保存的B实体。您可以将代码发布到删除它的位置吗?@SimonMartinelli,而不是existing.setB(object.getB());我添加了existing.setB(null)。但是它没有从db中删除已经保存的B。您还调用了A.children.remove(B)?我更改了代码,`for(B对象:existingA.getB()){existing.removeChild(对象);}updatedA=aDao.update(现有);`但是更新数据仍然有我早先保存的数据,你有交易吗?你是什么意思?我正在使用aDao.update()。@Transactional public T update(T entity){entity=entityManager.merge(entity);entityManager.flush();entityManager.refresh(entity);return entity;}更新A对象。愚蠢的问题:您正在使用Spring引导。你为什么不使用JpaRepository?
public class A {
// existing code
// Convenience mehtods
public void addChild(B b) {
children.add(b);
b.setA(this);
}
public void removeChild(B b) {
children.remove(b);
b.setA(null);
}
}