title: JPA: Foreign key constraint on delete
body: <p>I have the following relationship</p>
  
  <pre><code>Class UserAccount{
  //Other fields
  @OneToMany(mappedBy = "userAccount", cascade = CascadeType.REMOVE)
  private Set&lt;Images&gt; imagesShared;
  
  @ManyToMany
  @JoinTable(name = "USER_LIKES", joinColumns = @JoinColumn(name = "USER_NAME"),   inverseJoinColumns = @JoinColumn(name = "ID"))
  private Set&lt;Images&gt; imagesLiked;
  }
  
  Class Images{
  //other fields
  @ManyToMany(mappedBy = "imagesLiked")
  private Set&lt;UserAccount&gt; likes;
  }
  </code></pre>
  
  <p>I get an exception after these lines</p>
  
  <pre><code>Hibernate: delete from IMAGES where ID=?
  Hibernate: delete from COMMENTS where COMMENT_ID=?
  Hibernate: delete from COMMENTS where COMMENT_ID=?
  Hibernate: delete from COMMENTS where COMMENT_ID=?
  Hibernate: delete from COMMENTS where COMMENT_ID=?
  Hibernate: delete from COMMENTS where COMMENT_ID=?
  Hibernate: delete from IMAGES where ID=?
  </code></pre>
  
  <p>Exception:</p>
  
  <pre><code>Cannot delete or update a parent row: a foreign key constraint fails (`testdb`.`USER_LIKES`, CONSTRAINT `FKC6704E28B4E3D8B` FOREIGN KEY (`ID`) REFERENCES `IMAGES` (`ID`))
  </code></pre>
  
  <p>From my understanding this happens when JPA tries to remove <code>imagesShared</code>. 
  I tried doing this:</p>
  
  <pre><code>for (Images image : userAccount.getImagesShared()){
              image.setLikes(null);
          }
  em.remove(account);
  </code></pre>
  
  <p>But same error. Anyone?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>When I add this line it works fine.</p>
  
  <pre><code> for (Images image : userAccount.getImagesShared()){
              image.setLikes(null);
          }
  userAccount.getImagesShared().clear();
  em.remove(account);
  </code></pre>
  
  <p>But what is the difference between the remove operation that JPA does and what I do?</p>