Delete orphaned objects on the many side in Hibernate

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

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.