开发者

hibernate doesn't remove child with named query, but removes with session.delete()

I am not an expert with hibernate, as stated in the subject, I have an Object with a Collection of object in it. I tried to use a

session.delete(myObject) 

and the entity with all the related children gets correctly removed 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 t开发者_JS百科hen in the code

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

but only the main entity is removed, while the children remain in the database. The collection is correctly marked as delete-orphan. I wanted to know why such behaviour, and if it's possible how to achieve the complete removal with named queries.


This is a known issue, hibernate does not perform cascade delete via HQL. If you load the object and delete it using session.delete(object); then the cascade relations are respected. Not via HQL. You have either of the 3 options.

  • Load them and call session.delete();
  • Load all the child items via HQL, delete them, and then the real objects.
  • Put a cascade link at the database level. So when you delete it, the DB will take care of it.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜