11

I am stuck trying to get a query (QueryDSL) to work that gives me a count of distinct categories. For example, what I am trying to achieve:

categoryA -> 10 entries
categoryB -> 20 entries

This is what i have so far:

query().from(application)
            .transform(groupBy(application.category).as(list(application)));

However, this gives me for each category a list of all whole entries, I just want to get a count of this.

I tried messing around with count() but no luck.

Anybody know how to do this?

Farvardin
  • 5,336
  • 5
  • 33
  • 54
Wouter Willems
  • 432
  • 2
  • 6
  • 19

4 Answers4

27

Note that as of Querydsl 4.x, the accepted answer by Timo Westkämper is no longer valid. Breaking changes in Querydsl 4.0 have removed the query.list() method.

A solution working with Querydsl 4.0+ would now be:

query.from(application)
     .groupBy(application.category)
     .select(application.category, application.category.count())
     .fetch();
Community
  • 1
  • 1
SputNick
  • 1,231
  • 5
  • 15
  • 26
11

transform combined groupBy is meant to construct tree structures out of flat result sets. What you need can be easier expressed as

query.from(application)
     .groupBy(application.category)
     .list(application.category, application.category.count())
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111
5

If using 4.1.4, you may need to use a JPAQueryFactory instead of JPAQuery

If using JPAQuery, there is no select() or fetch() on the return from groupBy.

JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);

queryFactory
     .select(application.category, application.category.count())
     .from(application)
     .groupBy(application.category)
     .fetch();
nclord
  • 1,287
  • 1
  • 16
  • 17
0

In QueryDSL 4.4.0:

query.from(application)
   .groupBy(application.category)
   .transform(GroupBy.groupBy(application.category)).as(application.category.count()))

Learn more on: https://www.tabnine.com/code/java/methods/com.querydsl.jpa.JPQLQuery/transform

Jallow
  • 1
  • 2