【问题标题】:One to Many Bidirectional mapping for already persisted data in HibernateHibernate中已经持久化数据的一对多双向映射
【发布时间】:2021-08-28 07:47:23
【问题描述】:

我正在尝试使用已经持久化的子对象更新我的父类。

@Entity
public class Parent {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @OneToMany(mappedBy = "parent")
  private Set<Child> children = new HashSet<>();

  public void addChild(Child child){
     this.children.add(child);
     child.setParent(this);
  }
}

@Entity
public class Child {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="parent_id")
  private Parent parent;

  public void setParent(Parent parent) {
    this.parent = parent;
  }
}

...

Seeder logic
@Autowired
private ParentRepository parentRepository;
@Autowired
private ChildRepository childRepository;

Child c1 = new Child();
childRepository.save(cr1);

Parent p1 = new Parent();
p1.addChild(c1)
parentRepository.save(p1);

此代码段运行,但它从不更新子表中的 parent_id,并且始终显示为 Null。 当我将级联全部添加到父类时,它给了我detached entity passed error,因为孩子已经存在。删除所有级联并添加 CascadeType.MERGE 使代码运行,但子项中的外键仍然为空。

@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)

因此,我该如何处理这种情况?在我的场景中,孩子将在父母之前出现在数据库中。

【问题讨论】:

    标签: spring-boot hibernate nhibernate-mapping


    【解决方案1】:

    使用 CascadeType.ALL 时:@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)

    你只需要这样做来保存操作:

    @Autowired
    private ParentRepository parentRepository;
    
    Child c1 = new Child();
    Parent p1 = new Parent();
    p1.addChild(c1)
    parentRepository.save(p1);
    

    会没事的。

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 1970-01-01
      • 2020-05-22
      • 2021-10-16
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2014-11-15
      相关资源
      最近更新 更多