Hibernate: How to insert OneToMany children by cascade

I needed a way to insert an entity with a new joined (children) entity together. One way to do it is by separate the actions (e.g. to save the joined entity first and then to save the main entity).
However, Hibernate support inserting a new entity with new joined entity.

I would like to present a way to insert new parent element together with its new OneToMany children by cascade:

The parent Hibernate entity:

@Entity
@Table(name = "Parent")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Parent {
    ...
    @Override
    @Id    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column( name="Parent_ID", unique = true, nullable = false, updatable = false )
    public Integer getId() { return id; }
    private Long id;
 
    @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL,CascadeType.PERSIST,CascadeType.MERGE }, mappedBy = "parent")
    @Column(nullable = false)
    public List<Children> getChildrens() { return childrens; }
    public void setChildrens( List<Children> childrens) { this.childrens = childrens; }
    private List<Childrens> childrens;
}

The children Hibernate entity:

@Entity
@Table(name = "Children")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Children  {
   ...
   @ManyToOne( fetch = FetchType.EAGER )
   @JoinColumn(name = "parent_id", nullable = false )
   public Parent getParent() { return parent; }
   public void setTitle(Title title) {
       this.parent = parent;
   }
   private Parent parent;
 
}

In the Java code:

Don’t forget to set the parent in the children entity.
For example:

    Parent parent;// getting the Hibernate entity of the parent
    ...
    List<Children> childrenList = new ArrayList<Children>();
    Children children;
    children = new Children();
    children.set...
    children.setParent( parent );
    childrenList.add(children);
    title.setChildrens(childrenList);
One Comment
  1. Matthieu R. says:

    According to Hibernate documentation :

    CascadeType.ALL is a mix of all operations. So, I think that you can just use : cascade={CascadeType.ALL} for your entity “parent”.

    But, thanks for this little tip.

Leave a Reply

*