Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I let JPA or the database cascade deletions?

Let's say we have two entities, A and B. B has a many-to-one relationship to A like follows:

@Entity
public class A {
  @OneToMany(mappedBy="a_id")
  private List<B> children;
}

@Entity
public class B {
  private String data;
}

Now, I want to delete the A object and cascade the deletions to all its children B. There are two ways to do this:

  1. Add cascade=CascadeType.ALL, orphanRemoval=true to the OneToMany annotation, letting JPA remove all children before removing the A-object from the database.

  2. Leave the classes as they are and simply let the database cascade the deletion.

Is there any problem with using the later option? Will it cause the Entity Manager to keep references to already deleted objects? My reason for choosing option two over one is that option one generates n+1 SQL queries for a removal, which can take a prolonged time when object A contains a lot of children, while option two only generates a single SQL query and then moves on happily. Is there any "best practice" regarding this?

like image 544
Rasmus Franke Avatar asked Apr 26 '11 08:04

Rasmus Franke


1 Answers

I'd prefer the database. Why?

  • The database is probably a lot faster doing this
  • The database should be the primary place to hold integrity and relationship information. JPA is just reflecting that information
  • If you're connecting with a different application / platform (i.e. without JPA), you can still cascadingly delete your records, which helps increase data integrity
like image 180
Lukas Eder Avatar answered Oct 15 '22 05:10

Lukas Eder