title: JPA delete fails (integrity constraint violation: foreign key no action) - data model too convoluted?
body: <p>I'm experiencing a problem I cannot get my head around. I really hope someone out there can help. </p>
  
  <h3>Entity model</h3>
  
  <p>This might get a little meta as my data model represents programming objects. I've got three entities: Program, Clazz and Method. Classes can have multiple methods and occasionally inherited some other methods (from other classes).</p>
  
  <pre><code>@Entity
  public class Program {
  
      @OneToMany(mappedBy="program", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
      @OrderBy("name ASC")
      private Set&lt;Clazz&gt; clazzes = new TreeSet&lt;Clazz&gt;();
  }
  
  @Entity
  public class Clazz {
  
      @ManyToOne
      private Program program;
  
      @OneToMany(mappedBy="clazz", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
      @OrderBy("name ASC")
      private Set&lt;Method&gt; methods = new TreeSet&lt;Method&gt;();
  
      @ManyToMany(fetch=FetchType.LAZY, mappedBy="inheritedBy")
      @OrderBy("name ASC")
      private Set&lt;Method&gt; inheritedMethods = new TreeSet&lt;Method&gt;();
  
      @PreRemove
      private void tearDown() {
          inheritedMethods.clear();
      }
  
  }
  
  @Entity @Table(name="sf_method")
  public class Method {
  
      @ManyToOne(optional=true)
      private Clazz clazz;
  
      @ManyToMany(fetch=FetchType.LAZY)
      @JoinTable(name = "sf_method_inherited_by_class", 
          joinColumns = { @JoinColumn(name = "sf_method_inherited_by_class") }, 
          inverseJoinColumns = { @JoinColumn(name = "sf_class_inherits_method") }
      )
      private Set&lt;Clazz&gt; inheritedBy = new HashSet&lt;Clazz&gt;();
  
      @PreRemove
      public void tearDown() {
          inheritedBy.clear();
      }
  
  }
  </code></pre>
  
  <h3>My problem: what I do</h3>
  
  <p>What I need to do is to delete a program, including all its classes and methods. I use Spring-JPA repositories, so my code is:</p>
  
  <pre><code>@Autowired ProgramRepository programs;
  
  @Transactional(readOnly=false)
  public void forceDelete(Program p) {
      Set&lt;Clazz&gt; myClasses = p.getClazzes();
      for (Clazz c : myClasses) {
          logger.info("Clazz " + c.getName());
          for (Method m : c.getMethods()) {
              m.setClazz(null);
              methods.save(m);
          }
      }
      programs.delete(p);
  }
  </code></pre>
  
  <h3>What happens</h3>
  
  <p>The delete code works only in some circumstances. Sometimes I get the following error.</p>
  
  <blockquote>
    <p>SqlExceptionHelper - integrity constraint violation: foreign key no
    action; FKIBMDD2FV8TNJAF4VJTOEICS73 table: SF_METHOD AbstractBatchImpl
    - HHH000010: On release of batch it still contained JDBC statements</p>
  </blockquote>
  
  <p>Any idea? I spent so many hours on this and I failed every single resolution attempt. What am I doing wrong?</p>