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

4

我正在使用Spring data 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 repository 是任何的。
public interface UserRepository extends JpaRepository<UserEntity, Long>, 
      JpaSpecificationExecutor<UserEntity> {
}

那么我如何通过Spring Data进行聚合查询呢?我在文档中没有找到任何相关内容。

4个回答

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();
}

这样我们就可以获得聚合数据以及实际计数(聚合记录)。

5

1
你列出的第二个已经更新,反映了从Spring Data 1.7开始,countby谓词已被添加。 - chrismarx

1

你还可以使用@NativeQuery选项


0

在Spring Data中,您可以使用@Query为不支持的方法编写自定义查询。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接