Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Delete all children with one query

TL;DR: Is it possible to configure Hibernate to delete all child objects using a single delete query?


Full Question: I have the following parent/child association defined in Hibernate 5.1:

public class Parent {
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", cascade = CascadeType.REMOVE)
  private List<Child> children;
}

public class Child {
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "parent_id", nullable = false)
  private Parent parent;
}

When I delete the parent object, all of the child objects are deleted, as expected, but each one is deleted individually. In my application a parent could have many thousands of children, so for performance reasons I need to use a single query to delete them all at once.

Possible Workarounds

  1. Manually execute my own HQL query, DELETE FROM child WHERE parent_id = ?, prior to deleting the parent. The downside here is that I (and any other developers) have to remember to call the method. Plus, it essentially circumvents the cascade delete.
  2. Allow the cascade delete to happen at the database level. Since data is changing behind the scenes, I assume I would need to remember to manually .clear() the child collection to prevent disparity between Hibernate and the database.

Edit: I see older versions of Hibernate used to have the concept of a one-shot delete but I cannot find anything similar in the documentation for the latest version. Has that functionality been removed?

like image 706
Adam Parod Avatar asked Feb 23 '16 16:02

Adam Parod


1 Answers

  1. Say you delete a Parent.
  2. If some other table, say GrandChild, has a foreign key constraint with Child, with each Child having multiple GrandChild records, they need to be removed too.
  3. The reason for multiple generated delete queries is, Hibernate can not know whether there are any foreign key constraints from other tables, to the "Child" table. Also there might be some call back methods that needs to executed such as @PreRemove. This is the reason why each Child reference is loaded from the database and removed individually.
  4. In short, if you depend on Hibernate to manage your entities, this is the default behavior.
  5. Either set the ON DELETE CASCADE in the data base explicitly, or mark the required Child entity with the annotation @org.hibernate.annotations.OnDelete, which automatically adds the "on delete" to schema during the schema generation. For your example it would be,

    `@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", 
                cascade = CascadeType.REMOVE)    
     @org.hibernate.annotations.OnDelete(
                action = @org.hibernate.annotations.OnDeleteAction.CASCADE)
     private List<Child> children;
    
like image 107
Aravamudhan Avatar answered Sep 30 '22 17:09

Aravamudhan