【发布时间】: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