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?
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.
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.
To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With