JPA entity deletion operation does not work

When I try to make entityManager.remove (instance), the underlying JPA provider issues a separate delete operation for each GroupUser object. I believe that this is not the case in terms of performance, because if the Group has 1000 users, 1001 calls will be created to delete the entire group and grouprus itr object.

Would it make sense to write a named query to delete all the entries in the groupuser table (for example, delete from group_user, where group_id =?), So I would have to make only 2 calls to delete the group.

@Entity @Table(name = "tbl_group") public class Group { @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @Cascade(value = DELETE_ORPHAN) private Set<GroupUser> groupUsers = new HashSet<GroupUser>(0); 
+7
performance hibernate jpa
source share
2 answers

The simple answer is yes. If you want to delete Group , and you know that there are tons of records in the GroupUser table, then it is much better to create a delete request that will do everything in one batch, rather than one and one.

If you do not have cascading in the base database (or even if you do), its good practice to do this in the correct order.

So, first uninstall GroupUser .
Assuming you have a Group object that you want to delete.

 int numberDeleted = entityManager.createQuery("DELETE FROM GroupUser gu WHERE gu.group.id=:id").setParameter("id",group.getId()).executeUpdate(); 

The returned int indicates how many records are deleted.

Now you can finally delete Group

 entityManager.remove(group); entityManager.flush(); 

UPDATE

It seems that @OnDelete on @OneToMany does the trick

+8
source share

Since GroupUser can also have cascades, I don’t think there is a way to tell hibernate to batch delete them through the configuration.

But if you are sure that there is no cascade=DELETE on GroupUser , feel free to issue a HQL / JPA-QL request:

 DELETE FROM GroupUser WHERE group=:group 

If there are cascades, process them also with a request.

+2
source share

All Articles