Does Spring Data JPA have any way to count entites using method name resolving?

后端 未结 12 829
耶瑟儿~
耶瑟儿~ 2020-12-04 08:38

Spring Data JPA supports counting entities using specifications. But does it have any way to count entities using method name resolving? Let\'s say I want a method cou

相关标签:
12条回答
  • 2020-12-04 09:10

    As of Spring Data 1.7.1.RELEASE you can do it with two different ways,

    1) The new way, using query derivation for both count and delete queries. Read this, (Example 5). Example,

    public interface UserRepository extends CrudRepository<User, Integer> {
        Long countByName(String name);
    }
    

    2) The old way, Using @Query annotation.
    Example,

    public interface UserRepository extends CrudRepository<User, Integer> {
        @Query("SELECT COUNT(u) FROM User u WHERE u.name=?1")
        Long aMethodNameOrSomething(String name);
    }
    

    or using @Param annotation also,

    public interface UserRepository extends CrudRepository<User, Integer> {
        @Query("SELECT COUNT(u) FROM User u WHERE u.name=:name")
        Long aMethodNameOrSomething(@Param("name") String name);
    }
    

    Check also this so answer.

    0 讨论(0)
  • 2020-12-04 09:11

    As long as you do not use 1.4 version, you can use explicit annotation:

    example:

    @Query("select count(e) from Product e where e.area.code = ?1")
    long countByAreaCode(String code);
    
    0 讨论(0)
  • 2020-12-04 09:11

    This feature has been added in version 1.4 M1

    0 讨论(0)
  • 2020-12-04 09:13

    Working example

    @Repository
    public interface TenantRepository extends JpaRepository< Tenant, Long > {
        List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
        long countByTenantName(String tenantName);
    }
    

    Calling from DAO layer

    @Override
    public long countByTenantName(String tenantName) {
        return repository.countByTenantName(tenantName);
    }
    
    0 讨论(0)
  • 2020-12-04 09:14

    Thanks you all! Now it's work. DATAJPA-231

    It will be nice if was possible to create count…By… methods just like find…By ones. Example:

    public interface UserRepository extends JpaRepository<User, Long> {
    
       public Long /*or BigInteger */ countByActiveTrue();
    }
    
    0 讨论(0)
  • 2020-12-04 09:15

    If anyone wants to get the count with based on multiple conditions than here is a sample custom query

    @Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
        long countUrlsBetweenDates(User user, Date date1, Date date2);
    
    0 讨论(0)
提交回复
热议问题