java 按计数查询 dsl 转换器组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26723376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:28:34  来源:igfitidea点击:

querydsl transformer group by count

javasqlquerydsl

提问by Wouter Willems

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:

我被困在试图让查询 (QueryDSL) 工作,让我对不同类别进行计数。例如,我想要实现的目标:

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.

我试着乱搞,count()但没有运气。

Anybody know how to do this?

有人知道怎么做吗?

回答by SputNick

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.

请注意,从Querydsl 4.x 开始,Timo Westk?mper 接受的答案不再有效。Querydsl 4.0 中的重大更改删除了 query.list() 方法

A solution working with Querydsl 4.0+ would now be:

使用 Querydsl 4.0+ 的解决方案现在是:

query.from(application)
     .groupBy(application.category)
     .select(application.category, application.category.count())
     .fetch();

回答by Timo Westk?mper

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

转换组合 groupBy 旨在从平面结果集构建树结构。你需要什么可以更容易地表达为

query.from(application)
     .groupBy(application.category)
     .list(application.category, application.category.count())

回答by nclord

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

如果使用 4.1.4,您可能需要使用JPAQueryFactory而不是JPAQuery

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

如果使用 JPAQuery,则 groupBy 返回时没有 select() 或 fetch()。

JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);

queryFactory
     .select(application.category, application.category.count())
     .from(application)
     .groupBy(application.category)
     .fetch();