7

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.
Jay Anderson
  • 937
  • 1
  • 8
  • 18

1 Answers1

1

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.

Benson
  • 27
  • 1
  • 7
  • 3
    You will fetch all the entities and then delete them. Is there a way to delete directly? – Mark Jun 15 '21 at 13:30