简体   繁体   English

使用 @manytoone 和 @.netomany 关系保存嵌套对象 hibernate

[英]Saving nested objects with hibernate using @manytoone and @onetomany relations

I'have the following set up:我有以下设置:

class Parent{
   @Id
   @GeneratedValue
   @Column(name = "id", nullable = false)
   private Integer id;

   @JsonManagedReference
   @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
   private Set<Child>;
}
class Child {
   @Id
   @GeneratedValue
   @Column(name = "id", nullable = false)
   private Integer id;

   @ManyToOne(cascade = {CascadeType.REMOVE}, fetch = FetchType.LAZY)
   @JoinColumn(name = "parent_id")
   @OnDelete(action = OnDeleteAction.CASCADE)
   @JsonBackReference
   private Parent parent;

   @OneToMany(mappedBy = "child",  cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
   @JsonManagedReference
   private Set<GrandChild>;
}
class GrandChild {
   @Id
   @GeneratedValue
   @Column(name = "id", nullable = false)
   private Integer id;

   @ManyToOne(cascade = CascadeType.REMOVE)
   @JoinColumn(name = "child_id")
   @JsonBackReference
   private Child child;
}

All of the classes has the following annotations:所有类都有以下注释:

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@With
@Entity
@Table(name='each table name')

When I send a Json containing the Parent inside Childs and inside GrandChilds I can't save it, cause the parent_id column in the child cannot be null. Then I tried the approach to save the parent first and then just add the set of Childs, but the same thing is happening with GrandChild (child_id cannot be null).当我发送一个 Json,其中包含 Childs 和 GrandChilds 中的 Parent 时,我无法保存它,因为 child 中的 parent_id 列不能是 null。然后我尝试了先保存父级然后再添加 Childs 集的方法,但同样的事情也发生在 GrandChild 身上(child_id 不能为 null)。 Is there a way I can configure the hibernate to first save the parent, retrieve the ID, set it to the Child then save the child and then set ChildId to the GrandChild?有没有一种方法可以配置 hibernate 先保存父项,检索 ID,将其设置为子项,然后保存子项,然后将 ChildId 设置为 GrandChild? I started with saving first the Parent and then then set the set of childs to it and save it again (making update) and this was working, but when I add the GrandChilds it stops working.我开始首先保存 Parent,然后将一组子项设置到它并再次保存(进行更新)并且这是有效的,但是当我添加 GrandChilds 时它停止工作。 I can't (without polluting the objects) make same thing for the GrandChilds cause I'll not have the connection which is where.我不能(不污染对象)为 GrandChilds 做同样的事情,因为我没有连接在哪里。

My setup is ok, but I was using immutable objects when setting parent to the Child object and Child to GrandChild.我的设置没问题,但是在将父级设置为子级 object 并将子级设置为孙级时,我使用的是不可变对象。 When I changed from with to set it started working当我从 with 更改为 set 时,它开始工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM