简体   繁体   中英

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?

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

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/

这完全取决于您在图书收藏集中定义的层叠属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM