6

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?

Preslav Rachev
  • 3,983
  • 6
  • 39
  • 63

3 Answers3

5

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).

Stefano Travelli
  • 1,889
  • 1
  • 15
  • 18
2

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/

unludo
  • 4,912
  • 7
  • 47
  • 71
0

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

Kurt Du Bois
  • 7,550
  • 4
  • 25
  • 33