Note that there are some explanatory texts on larger screens.

plurals
  1. POHibernate deleting orphans when updating collection
    text
    copied!<p>I'm finding that orphan records aren't being deleted when removing from a collection in Hibernate. I must be doing something simple wrong, (this is Hibernate-101!), but I can't find it..</p> <p>Given the following:</p> <pre><code>public class Book { @ManyToOne @NotNull Author author; } public class Author { @OneToMany(cascade={CascadeType.ALL}) List&lt;Book&gt; books; } </code></pre> <p>And the following update code:</p> <pre><code>Author author = authorDAO.get(1); Book book = author.getBooks().get(0); author.getBooks().remove(0); authorDAO.update(author); </code></pre> <p>AuthorDAO snippet:</p> <pre><code>@Override public void update(T entity) { getSession().update(entity); } </code></pre> <p>The following test the fails:</p> <pre><code>Author author = author.get(1); assertEquals(0,author.getBooks().size()); // Passes Book dbBook = bookDAO.get(book.getId()) assertNull(dbBook); // Fail! dbBook still exists! assertFalse(author.getBooks().contains(dbBook) // Passes! </code></pre> <p>In summary, I'm finding:</p> <ul> <li>While book is removed from the Author's collection of books, it still exists in the database</li> <li>If I examine <code>book.getAuthor().getBooks()</code>, book does not exist in that collection</li> </ul> <p>This "feels" like I'm not flushing the session or forcing an update appropriately - but I'm not sure where I should be doing that. Along that vein, other points that may be impacting:</p> <ul> <li>I'm performing the above in a JUnit test decorated with <code>@RunWith(SpringJUnit4ClassRunner.class)</code></li> <li>I originally hit this problem inside an update routine which is decorated with <code>@Transactional</code>, however, I have since recreated it in a plain old JUnit test.</li> </ul> <p>Any advice would be greatly appreciated!</p> <p><strong>EDIT:</strong> Thanks for all the feedback already. Further to comments below, I've added the <code>@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)</code> to the parent, so it's now:</p> <pre><code>public class Author { @OneToMany(cascade={CascadeType.ALL}) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) List&lt;Book&gt; books; } </code></pre> <p>I'm still finding the same results. I MUST be missing something simple.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload