Search code examples
javahibernatejpamany-to-onehibernate-onetomany

JPA/Hibernate - delete child removes parent (from same table)


I have a class Comment (see below) with some Comment objects belonging to a parent Comment. So far, when I delete a parent Comment, the childs are also deleted (as expected), BUT the problem comes when a child is deleted because the parent is also removed. I guess the problem comes from the JPA configuration used in the class. Any ideas how to delete the childs without affecting the parent row?

 public class Comment {
   @Column  
   private String text;             

   @ManyToOne(cascade={CascadeType.ALL})
   private Comment parent;

   @OneToMany(cascade={CascadeType.ALL}, mappedBy="parent")
   private Set<Comment> childs = new HashSet<Comment>();
}

Cheers


Solution

  • Remove cascade={CascadeType.ALL} from mapping of parent:

    public class Comment {
       @Column  
       private String text;             
    
       @ManyToOne
       private Comment parent;
    
       @OneToMany(cascade=CascadeType.ALL, mappedBy="parent") // or orphanRemoval=true
       private Set<Comment> childs = new HashSet<Comment>();
    }