Skip to content

Hibernate bulk-delete does not cascade delete the associations

September 11, 2011
tags:

While trying to cascade delete an entity’s association, I learned that various Hibernate queries support cascade delete differently.

Deleting domain objects will delete the entity’s associations, but executing bulk delete of an entity does not.

Let’s start with an example setup of these two related entities:


@Entity public class Student {
   ...
   @ManyToMany
   @JoinTable (
   name = "students_courses",
  joinColumns = { @JoinColumn( name = "course_id" ) },
inverseJoinColumns = { @JoinColumn( name = "student_id" ) } )
   private Set<Course> courses;
 ...
}
@Entity public class Course {
   ...
   @ManyToMany( mappedBy = "courses" )
   private Set<Student> students;
   ...
}

The first rule to enable Hibernate cascade-delete is defining the associations in both entities. In this example, Student has a set of Course(s), and Course has a set of Student(s).

Generally speaking, we can delete Student(s) in 2 ways as the following:

1.  Fetch the Student objects from the DB, then delete them.


List<Student>students = someDao.getAll(Student.class);
for (Student student : students) {
student.courses.clear();
}
someDao.save(students);

2.  Bulk-delete Student data


String bulkDeleteQuery = "delete from students where <some criteria>";
getHibernateTemplate().bulkUpdate(bulkDeleteQuery);

However, #2 will throw a runtime exception as bulk delete does not delete the corresponding associations. It attempts to delete Students only. The error is of “Cannot delete or update a parent row: a foreign key constraint fails.”

There are a number of related questions online. Here is one on StackOverflow.

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: