Hibernate does not delete the child with the named query, but does delete with session.delete ()

I am not an expert with sleep mode, as indicated in the topic, I have an Object with a collection of objects in it. I tried to use

session.delete(myObject) 

and the entity with all its children is correctly deleted from the database.

However, when I run a simple named query:

 <query name="deleteByID"> DELETE FROM MyObject o WHERE o.objId IN (:objIds) </query> 

And then in code

 Query deleteQuery = s.getNamedQuery("deleteByID"); deleteQuery.setParameterList("objIds", objIds); return deleteQuery.executeUpdate(); 

but only the main object is deleted, and the children remain in the database. The collection is correctly marked as an orphan exception. I wanted to know why this behavior, and if possible, how to achieve a complete deletion using named queries.

+4
source share
1 answer

This is a known issue; hibernate does not perform cascading deletion via HQL. If you load an object and delete it using session.delete(object); , then the cascade relationship is respected. Not through HQL. You have one of 3 options.

  • Download them and call session.delete();
  • Download all the children via HQL, delete them, and then the real objects.
  • Place a cascading link at the database level. Therefore, when you delete it, DB will take care of it.

More details here: https://forum.hibernate.org/viewtopic.php?f=1&t=944722&start=0

+4
source

All Articles