0

I am a bit confused about the how to delete hibernate entity using HQL. I have entity Entity and this entity has multiple many-to-many/one-to-many mappings. If I delete Entity using the HQL query

Delete from Entity x where x.id = :id

will hibernate take care of deleting child objects and relationships specified in the entity's configuration file?

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
IWantMoore
  • 73
  • 1
  • 1
  • 10
  • 1
    This is a probably repitition of [this](http://stackoverflow.com/questions/7695831/how-can-i-cascade-delete-a-collection-which-is-part-of-a-jpa-entity/7696147#7696147) – OYRM Feb 02 '16 at 16:37

2 Answers2

0

If you have cascaded your class correctly hibernate must take care of your deleting operation. But only after committing changes. But if you are using hibernate it is better to delete entity than row in table

Dante
  • 279
  • 1
  • 19
  • I am using Hibernate. I was more interested in the functionality of HQL because I wanted to know if it would be possible to extend this statement to a bulk delete operation on many rows – IWantMoore Feb 02 '16 at 16:44
  • anyway hibernate must to delete all child records when parent record is deleted if your entity was cascaded with `cascadetype.remove` or `cascadetype.all` – Dante Feb 02 '16 at 16:46
  • Im talking about using HQL queries. From what I am seeing in my testing and http://stackoverflow.com/questions/7695831/how-can-i-cascade-delete-a-collection-which-is-part-of-a-jpa-entity/7696147#7696147, it does not appear to work with cascade. I get oracle exceptions notifying me that child records have been found, so the object cannot be deleted – IWantMoore Feb 02 '16 at 16:58
  • Ok. Look. Your sql database have a cascade option too. So if you want to delete an Entity via HQL query (not via session.delete(entity), what would be better), you need to go to database and make `ON DELETE CASCADE` for foreign key of your child table. In this case you will be able to delete a row in parent and all dependent rows in child table would be deleted too. http://www.java2s.com/Code/SQLServer/Constraints/DELETECASCADEandUPDATECASCADE.htm – Dante Feb 02 '16 at 18:11
0

Cascade option is useful in such cases. In Hibernate there are a number of cascading types: ALL,PERSIST, MERGE, REMOVE,REFRESH,DELETE,SAVE_UPDATE,etc. You can use them as per your specific need. Example: @OneToMany(mappedBy = "id",cascade = CascadeType.ALL)

Reference: https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/annotations/CascadeType.html

Snekhe
  • 64
  • 8