如何使用spring-data-jpa检索聚合函数查询

Eha*_*ati 4 java spring jpa spring-data spring-data-jpa

我正在使用Spring数据jpa 1.2,我无论如何都找不到像下面那样检索聚合查询结果.

select count(v), date(v.createTimestamp) from UserEntity v
    group by date(v.createTimestamp)
Run Code Online (Sandbox Code Playgroud)

哪个与原生JPA完美配合

@Entity()
public class UserEntity {

   @Id
   private long id;
   .
   .
   @Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
   private Timestamp createTimestamp;

}
Run Code Online (Sandbox Code Playgroud)

我的JPA存储库是

public interface UserRepository extends JpaRepository<UserEntity, Long>, 
      JpaSpecificationExecutor<UserEntity> {
}
Run Code Online (Sandbox Code Playgroud)

那么如何才能进行聚合查询抛出Spring数据,我在文档中找不到任何内容

Eha*_*ati 8

我找到了一种方法来做到这一点

public interface UserRepository extends JpaRepository<UserEntity, Long>, 
      JpaSpecificationExecutor<UserEntity> {

      @Query(value = "select count(v), date(v.createTimestamp) from UserEntity v group by date(v.createTimestamp)", 
             countQuery = "select count(1) from (select count(1) from UserEntity v group by date(v.createTimestamp)) z")
      public List<Object[]> findCountPerDay();
}
Run Code Online (Sandbox Code Playgroud)

这样我们就可以得到汇总数据和实际数量(汇总记录)