java 如何计算 QueryDSL 中特定字段上的不同项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9943992/
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
How to count distinct items on specific fields in QueryDSL
提问by Adrian Cox
Edit: it turns out that JPA can't express this. The solution was to rewrite in SQL.
编辑:事实证明,JPA 无法表达这一点。解决方案是用 SQL 重写。
I'm using QueryDSL to perform an aggregate query on a JPA data set for reporting. I have no problem extracting the report data. For example:
我正在使用 QueryDSL 对用于报告的 JPA 数据集执行聚合查询。我提取报告数据没有问题。例如:
...
query = query.groupBy(QVehicle.vehicle.make, QVehicle.vehicle.model);
return query.listDistinct(new QMakeModelReportData(
QVehicle.vehicle.make, QVehicle.vehicle.model,
QVehicle.vehicle.make.count()));
This produces a list of my DTO object, each of which contains a vehicle make, vehicle model, and the count of vehicles of that make model. Like this:
这会生成我的 DTO 对象的列表,每个对象都包含车辆品牌、车辆型号以及该品牌型号的车辆数量。像这样:
Ford, Focus, 14
Ford, Mondeo, 4
Vauxhall, Astra, 4
But I can't work out the syntax to count the number of rows before I actually perform the query. The syntax I imagine is like this, which doesn't exist:
但是在我实际执行查询之前,我无法计算出计算行数的语法。我想象的语法是这样的,它不存在:
return query.countDistinct(QVehicle.vehicle.make, QVehicle.vehicle.model);
I've ended up with a rather inefficient option:
我最终得到了一个相当低效的选择:
return query
.listDistinct(QVehicle.vehicle.make, QVehicle.vehicle.model)
.size();
Is there anything better?
有更好的吗?
采纳答案by Adrian Cox
This is not a QueryDSL limitation, but a JPA limitation. The solution was to rewrite in SQL.
这不是 QueryDSL 限制,而是 JPA 限制。解决方案是用 SQL 重写。
回答by Ali Saeed
You can do query.select(q.field.countDistinct())
你可以做 query.select(q.field.countDistinct())