title: JPA + Hibernate + Spring + OneToMany delete cascade
body: <p>I've read some related questions but they are not exactly the same problem as mine.</p>
  
  <p>I'm using JPA + Hibernate + Spring and I want to do something that I'm not sure if it is possible just with config.</p>
  
  <p>I have my domain classes with a more or less complicated relation. There are many elements that are related with one element (like if it was a tree many elements are sons of one element).</p>
  
  <p>Something like:</p>
  
  <pre><code>@Entity
  class Foo {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Integer id;
  
      @ManyToOne
      @JoinColumn(name = "PARENT_ID")
      private Foo parentNode;
      ...
  }
  </code></pre>
  
  <p>Which will get a table like:</p>
  
  <pre><code>Foo id    parent_id
  1
  2         1 
  3         1
  </code></pre>
  
  <p>When I delete row with id = 1 I want to delete rows with id = 2 and id = 3 (it may be recursive, elements with parent_id = 2 and parent_id = 3 would be deleted as well).</p>
  
  <p>For some restrictions I only can have the relation in son's side with the parent_id reference.</p>
  
  <p>My question is: is it possible to do this with JPA or Hibernate configuration or do I need to do some recursive function to delete all children and all parents?</p>
  
  <p>I've tried with:</p>
  
  <pre><code>@OneToMany(name = "PARENT_ID", cascade = CascadeType.REMOVE)
  </code></pre>
  
  <p>And I've read that maybe using Hibernate annotations.</p>
  
  <p>If anyone can give me some clue I'm lost at this point.</p>
  
  <h2>Edit 1</h2>
  
  <p>Would it be possible to do like:</p>
  
  <pre><code>@Entity
  class Foo {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Integer id;
  
      @ManyToOne
      @JoinColumn(name="PARENT_ID")
      private Foo parentNode;
  
      @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentNode", cascade = CascadeType.REMOVE, orphanRemoval = true)
      private Set&lt;Foo&gt; childs = new LinkedHashSet&lt;Foo&gt;();
      ...
  }
  </code></pre>
  
  <p>Keeping the table as is, with the fk to the parent?
  I've tried this but I keep getting the same error, fk restriction violated.</p>
  
  <h2>Edit 2</h2>
  
  <p>Finally solved with:</p>
  
  <pre><code>@Entity
  class Foo {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Integer id;
  
      @ManyToOne
      @JoinColumn(name = "PARENT_ID")
      private Foo parentNode;
  
      @OneToMany(mappedBy = "parentNode", cascade = CascadeType.REMOVE)
      private Set&lt;Foo&gt; childs = new LinkedHashSet&lt;Foo&gt;();
      ...
  }
  </code></pre>
  
  <p>This <code>@OneToMany</code> is needed even if we do the mapping in our BBDD by refering just the parent id.</p>
  
  <p>Now when we delete a Foo with childs, it's childs will be deleted as well.</p>
  
  <p>Thanks for your time and good advices!</p>