简体   繁体   中英

how to retrieve an aggregation function query with spring-data-jpa

I am using Spring data jpa 1.2 and I can't find anyway to retrieve an aggregate query result like the following one.

select count(v), date(v.createTimestamp) from UserEntity v
    group by date(v.createTimestamp)

Which work perfectly with the native JPA

@Entity()
public class UserEntity {

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

}

any my JPA repository is

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

so how can I do an aggregate queries throw Spring data, I find absolutely nothing in the documentation

I found a way to do this

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

This way we can get aggregate data along with actual count ( aggregated records )

你也可以使用@NativeQuery选项

你可以有@Query为春季数据的unsupporeted方法自定义查询。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM