4

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

4 Answers 4

8

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 )

Sign up to request clarification or add additional context in comments.

Comments

5

"countBy" is currently not supported in Spring Data:

Support to 'countBy' query methods

Does Spring Data JPA have any way to count entites using method name resolving?

1 Comment

The second you list actually has been updated to reflect that as of spring data 1.7, the countby predicate has been added
1

you can also use @NativeQuery option

Comments

0

You can have @Query for custom queries for your unsupporeted methods in spring-data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.