Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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?

like image 792
Preslav Rachev Avatar asked Feb 06 '12 10:02

Preslav Rachev


People also ask

What is remove method in hibernate?

In JavaDoc of Session class the description of delete method is: Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state.

What is Cascade delete in hibernate?

Use the @CascadeOnDelete annotation to specify that a delete operation performed on a database object is cascaded on secondary or related tables. ON DELETE CASCADE is a database foreign key constraint option that automatically removes the dependent rows.

How do I delete an entity in JPA?

To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.


1 Answers

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

like image 148
Stefano Travelli Avatar answered Oct 05 '22 08:10

Stefano Travelli