title: JPA deleting bidirectional association from inverse side
body: <p>In my domain model there are a lot of bidirectional associations (both OneToMany and ManyToMany)</p>
  
  <p>I've read <a href="http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/" rel="nofollow">this article</a> and made all my associations on the basis of the sample pattern. (the ManyToMany associations has a two-sided addXY methods, following the pattern)</p>
  
  <p>Using <a href="http://blog.xebia.com/2009/04/09/jpa-implementation-patterns-removing-entities/" rel="nofollow">the pattern in this article</a> the question is, what about deleting from the inverse side?</p>
  
  <p>Example:</p>
  
  <pre><code>public class Customer implements Serializable {
  
  ...
  
  @ManyToOne()
  private CustomerStatus customerStatus;
  
  
  @PreRemove
  public void preRemove(){
      setCustomerStatus(null);
  }
  
  public void setCustomerStatus(CustomerStatus customerStatus) {
      if(this.customerStatus != null) { this.customerStatus.internalRemoveCustomer(this); }
      this.customerStatus = customerStatus;
      if(customerStatus != null) { customerStatus.internalAddCustomer(this); }
  }
  </code></pre>
  
  <p>On the other side:</p>
  
  <pre><code>public class CustomerStatus implements Serializable {
  
  private static final long serialVersionUID = 1L;
  
  @OneToMany(mappedBy="customerStatus")
  private List&lt;Customer&gt; customers;
  
  @PreRemove
  public void preRemove(){
      for(Customer c : customers){
          c.setCustomerStatus(null); // this causes ConcurrentException
      }
  
  }
  
  public List&lt;Customer&gt; getCustomers() {
      return Collections.unmodifiableList(this.customers);
  }
  
  public void addCustomer(Customer c){
      c.setCustomerStatus(this);
  }
  
  public void removeCustomer(Customer c){
      c.setCustomerStatus(null);
  }
  
  void internalAddCustomer(Customer c){
      this.customers.add(c);
  }
  
  void internalRemoveCustomer(Customer c){
      this.customers.remove(c);
  }
  </code></pre>
  
  <p>The problem is, that the preRemove method causes <code>ConcurrentException</code>. How to handle this?
  The goal is, to delete the CustomerStatus, and set NULL all the Customers, where there was that status.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Without the preRemove method, I've got <code>MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails</code></p>