Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Repository Delete With Specification

Spring's CrudRepository provides some delete methods while JpaSpecificationExecutor does not. I'd like to delete based on a Specification -- just like I'm doing for querying. Is there a way to do this?

Justification: I want to be sure a user owns the resource during deletion instead of allowing direct access to the resource based on the id (see https://www.owasp.org/index.php/Top_10_2013-A4-Insecure_Direct_Object_References).

Options I see:

  • Use @Query on a custom delete method in the repository. Something like delete from Entity e where e in (select e from Entity e where ...). This works fine, but I'd like to re-use other code and not have to manually create the query.
  • Fetch the entities then delete them. This seems wasteful to fetch and then delete when it can be done in one go.
like image 800
Jay Anderson Avatar asked Aug 15 '26 19:08

Jay Anderson


1 Answers

Its simple you can use List<YourReturnType> result = yourRepository.findAll(specification); to query your records and then use yourRepository.deleteAll(result); to delete all those records.

like image 152
Benson Avatar answered Aug 18 '26 09:08

Benson