How to shorten names of query methods in Spring Data JPA Repositories?

前端 未结 2 1349
半阙折子戏
半阙折子戏 2020-12-14 02:30

Consider a Spring Data Jpa Repository:

public interface UserRepository extends JpaRepository {

           


        
相关标签:
2条回答
  • 2020-12-14 02:43

    Use default Java 8 feature for wrapping, just like so:

    // use findOneByEmail instead
    User findOneByDeletedIsFalseAndEmail(String email);
    
    default User findOneByEmail(String email) {
        return findOneByDeletedIsFalseAndEmail(email);
    }
    

    See an example.

    0 讨论(0)
  • 2020-12-14 02:54

    Now you can use Java 8 default interface methods as @Maksim Kostromin described. But there is no such a feature in Spring.

    -- Old answer

    There is no such a way. You can specify any name for a method and add an annotation @Query with parameter value which holds desired query to database like this:

    @Query(value="select u from User u where u.deleted=false and u.email=:email")
    User findOneByEmail(@Param("email")String email);
    

    or, with native sql query:

    @Query(value="SELECT * FROM users WHERE deleted=false AND email=?1", nativeQuery=true)
    User findOneByEmail(String email);
    

    You can also use names that follow the naming convention for queries since @Query annotation will take precedence over query from method name.

    @Query docs

    Upd:

    from Spring docs:

    Although getting a query derived from the method name is quite convenient, one might face the situation in which ... the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention ... or rather annotate your query method with @Query.

    0 讨论(0)
提交回复
热议问题