0

What I want is a way for Hibernate to generate 1 statement to delete all children, instead of 1 statement per child.

If I have a relationship between Entity A and B , where A is the parent and B can be many children. If I use annotations such as OrphanRemoval or OnCascade delete on the entity relationship, when I delete the parent the sql that gets automatically generated says

delete from table where id=?  - per child

What I want Hibernate to do is generate sql like

delete from table where id in (child1,child1)

Is there an annotation or setting I can use to do this easily?

I feel I'm not the first person to run into this issue, but I cant find any way to solve it other then writing my own sql and removing the annotations.

MrClamps
  • 31
  • 9

1 Answers1

1

You can't do that with entityManager.remove() but you can use executeUpdate():

Query q = entitiyManager.createQuery("delete from MyEntity m where m.id in :ids)");
q.setParameter("id", <list of ids>);
q.executeUpdate();

Read more in the documentation: https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#batch-bulk-hql-update-delete

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • This looks like its executing an sql that I write, but does this take into account my parent, child scenario from above? – MrClamps Dec 08 '21 at 17:52
  • Yes. This is not SQL this is JPQL and operates on the Entity model. I changed the answer to reflect that better – Simon Martinelli Dec 08 '21 at 18:49
  • This query is deleting using "in" I assume this means this query is to delete the child objects and that its something I have to manually call.But what I have in my example is removeOrphan for example or I could be using cascade.delete annotation, when I delete my parent object I want the sql hibernate creates for that child relation to only execute 1 query for all children. – MrClamps Dec 09 '21 at 09:34
  • Have you tried it? – Simon Martinelli Dec 09 '21 at 09:49