Spring Data: “delete by” is supported?

后端 未结 9 2274
长情又很酷
长情又很酷 2020-11-28 20:57

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 hopi

9条回答
  •  星月不相逢
    2020-11-28 21:33

    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 {
        @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 {
    
        Long countByFirstName(String firstName);
    
        Long deleteByFirstName(String firstName);
    
        List removeByFirstName(String firstName);
    
    }
    

提交回复
热议问题