【问题标题】:how to retrieve an aggregation function query with spring-data-jpa如何使用 spring-data-jpa 检索聚合函数查询
【发布时间】:2013-02-05 06:05:23
【问题描述】:

我正在使用 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 存储库都是

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

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

【问题讨论】:

    标签: java spring jpa spring-data spring-data-jpa


    【解决方案1】:

    【讨论】:

    • 您实际上列出的第二个已经更新,以反映从 Spring Data 1.7 开始,添加了 countby 谓词
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我找到了办法

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

      这样我们可以得到聚合数据和实际计数(聚合记录)

      【讨论】:

        【解决方案4】:

        你也可以使用@NativeQuery选项

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-24
          • 1970-01-01
          • 2018-07-25
          • 2014-03-05
          • 2015-11-10
          • 2017-10-09
          • 2014-12-02
          • 1970-01-01
          相关资源
          最近更新 更多