Why does a manually defined Spring Data JPA delete query not trigger cascades?

对着背影说爱祢 提交于 2019-12-04 20:09:23
Oliver Drotbohm

This has got nothing to do with Spring Data JPA but is the way JPA specifies this to work (section 4.10 - "Bulk Update and Delete Operations", JPA 2.0 specification):

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

If you think about it, JPA cascades are not database-level cascades but ones maintained by the EntityManager. Hence, the EntityManager needs to know about the entity instance to be deleted and its related instances. If you trigger a query, it effectively can't know about those as the persistence provider translates it into SQL and executes it. So there's no way the EntityManager can analyze the object graph as the execution is completely happening in the database.

A question and answer related to this topic here can be found over here.

I had the same problem and to solve this I added the property clearAutomatically in the @Modifying annotation with true value.

@Modifying(clearAutomatically = true)
@Query("delete User u where u.id = :userId")
void deleteUserById(@Param("userId") Long userId);

Besides that, the service method that deletes the entity is annotated with @Transaction and the method that inserts the user as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!