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

时间:2013-02-20 09:33:53

标签: 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)

与原生JPA完美配合

@Entity()
public class UserEntity {

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

}

我的任何JPA存储库都是

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

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

4 个答案:

答案 0 :(得分: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();
}

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

答案 1 :(得分:5)

答案 2 :(得分:1)

您也可以使用@NativeQuery选项

答案 3 :(得分:0)

您可以使用 @Query 对spring-data中的 unsupporeted 方法进行自定义查询。