title: Should I let JPA or the database cascade deletions?
body: <p>Let's say we have two entities, A and B. B has a many-to-one relationship to A like follows:</p>
  <pre><code>@Entity
  public class A {
    @OneToMany(mappedBy=&quot;a_id&quot;)
    private List&lt;B&gt; children;
  }
  
  @Entity
  public class B {
    private String data;
  }
  </code></pre>
  <p>Now, I want to delete the <code>A</code> object and cascade the deletions to all its children <code>B</code>. There are two ways to do this:</p>
  <ol>
  <li><p>Add <code>cascade=CascadeType.ALL, orphanRemoval=true</code> to the OneToMany annotation, letting JPA remove all children before removing the A-object from the database.</p>
  </li>
  <li><p>Leave the classes as they are and simply let the database cascade the deletion.</p>
  </li>
  </ol>
  <p>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 &quot;best practice&quot; regarding this?</p>