【问题标题】:How to update child entity when updating parent in one to many relationship?在一对多关系中更新父实体时如何更新子实体?
【发布时间】:2019-01-23 10:26:34
【问题描述】:

我有两个实体,分别称为 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)
    @JoinColumn(name="a_id")
    @JsonIgnore
    private A child;
}

我想在更新 A 类时更新 B 类。现在让我们说,我在 A 中有 3 个 B 实例。更新时我想从中删除一个实例。但是现在,它没有发生。但是,如果我需要向 A 添加一个新的 B,它就可以工作。我做错了什么?请告诉我。 为了更新我使用下面的实体。

public update A(A object){
    A existing = aDao.find(object.getID()) // retrieve the existing object A;
    for(B obj: object.getB()){  // this will create if there are new entities, but, i need to remove alreadet saved B instance if they are not in updated object
        obj.setA(existing);
    }
    existing.setB(object.getB());        
}

【问题讨论】:

  • 当您移除 A 中的 B 个孩子时,您是否将 B 中的孩子设置为 null?
  • @SimonMartinelli 我也这样做了,什么也没发生。 existing.setB(null) 这不会从数据库中删除已经保存的 B 实体
  • 你能把你删除的代码贴出来吗?
  • @SimonMartinelli,而不是 existing.setB(object.getB());我添加了 existing.setB(null) 。但它并没有从 db 中删除已经保存的 B。
  • 你还调用A.children.remove(B)?

标签: hibernate spring-boot jpa one-to-many


【解决方案1】:

确保对 A 中的子级调用 remove 并将 B 中的子级设置为 null:

a.getChildren().remove(b);
b.setA(null);

一个很棒的东西是所谓的方便方法,您可以将其放在 A 中的一侧:

 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);
     }
 }

这样您的双向关系始终是最新的。

【讨论】:

  • 我更改了代码,` for (B object: existingA.getB()){ existing.removeChild(object); } updatedA = aDao.update(existing);` 但是updatedA还有我之前保存的数据
  • 你有交易吗?
  • 你是什么意思?我正在使用 aDao.update() 更新 A 对象。
  • @Transactional public T update(T entity) { entity = entityManager.merge(entity); entityManager.flush(); entityManager.refresh(实体);返回实体; }
  • 愚蠢的问题:您正在使用 Spring Boot。为什么不使用 JpaRepository?
猜你喜欢
  • 2013-07-24
  • 2015-01-26
  • 2016-11-16
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 2019-12-05
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多