Java : Delete orphaned objects on the many side in Hibernate

This page last changed on Mar 27, 2009 by Kees de Kooter

Goal

To delete the "orphaned" associated object on the many side of a one-to-many association. The ORM framework is Hibernate + Hibernate Annotations.

Solution

  • make the One side the owner of the relationship: avoid the mappedBy annotation propery
  • add the hibernate specific @Cascade annotation
  • prevent setting the collection directly

    public class Bar {
    
        @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
        @JoinColumn(name="barId")
        @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
        private List<Foo> foos;
    
        protected setFoos(List<Foo> foos) {
            this.foos = foos;
        }
    
        public void addFoo(Foo foo) {
            this.getFoos().add(foo);
            foo.setBar(this);
        }
    }

References