Preslav Rachev
Preslav Rachev

Reputation: 4003

Hibernate does not delete a DB record when an entity is removed from a collection

Simply removing an entity from a collection of related entities, will not delete the database record, right?

for example:

currentUser.getBooks().remove(thisBook);
userDAO.update(currentUser);

won't delete the record from the DB

Do I have to always explicitly go to the bookDAO and say session.delete(thisBook) every time? I though that Hibernate is much smarter than that and does cascading checks when a parent entity is saved or updated.

How do I resolve this?

Upvotes: 6

Views: 9336

Answers (3)

Stefano Travelli
Stefano Travelli

Reputation: 1927

Removing entity Book from the books collection in entity User just removes the relationship between the two entities (Book and User), not the Book entity instance.

The CASCADE clause is also not what you are looking for. Cascading means that if User has books, that is a collection of Book instances, when you remove a User instance, then the book instances are removed as well.

So, read getBooks().remove(thisBook) as remove this book from this collection and not from the database.

And yes, if you want to remove the book you have to use session.remove(book) (or the facility in you DAO).

Upvotes: 5

unludo
unludo

Reputation: 5010

You need to specify the cascade type on your relationship.

examples here: http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/

Upvotes: 1

Kurt Du Bois
Kurt Du Bois

Reputation: 7655

It all depends on the cascade attribute that you've defined on your books collection.

Upvotes: 0

Related Questions