javahibernatehibernate-cascade

How to setup update on cascade in hibernate 4 with javax.persistence.OneToMany?


I use hibernate 4.2.

It doesn't give me hibernate variant of OneToMany annotation, but only javax.persistence.OneToMany.

So I use it as

public class Parent  {
      ...........
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
        private Set<Child> children = new HashSet<Child>();

When I do update of Parent I expect children collection to be updated by cascade MERGE.

session.update(parent);

But it doesn't update Child entities of children collection. It only sends update statement for Parent entity.

So how can I update on cascade Child entities of children collection?

I cannot use org.hibernate.annotations.CascadeType because it is not supported by javax.persistence.OneToMany.


Solution

  • If you want to use hibernate's CascadeType, define @Cascade(..) separately on field/method level,

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    @Cascade({CascadeType.PERSIST, CascadeType.MERGE, CascadeType.SAVE_UPDATE}) //example
    private Set<Child> children = new HashSet<Child>();