Search code examples
springspring-dataspring-data-jpa

Spring Data: "delete by" is supported?


I am using Spring JPA for database access. I am able to find examples such as findByName and countByName, for which I dont have to write any method implementation. I am hoping to find examples for delete a group of records based on some condition.

Does Spring JPA support deleteByName-like delete? Any pointer is appreciated.

Regards and thanks.


Solution

  • Deprecated answer (Spring Data JPA <=1.6.x):

    @Modifying annotation to the rescue. You will need to provide your custom SQL behaviour though.

    public interface UserRepository extends JpaRepository<User, Long> {
        @Modifying
        @Query("delete from User u where u.firstName = ?1")
        void deleteUsersByFirstName(String firstName);
    }
    

    Update:

    In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, remove and count operations is accessible.

    public interface UserRepository extends CrudRepository<User, Long> {
    
        Long countByFirstName(String firstName);
    
        Long deleteByFirstName(String firstName);
    
        List<User> removeByFirstName(String firstName);
    
    }