[英]How to count distinct items on specific fields in QueryDSL
Edit: it turns out that JPA can't express this. 编辑:事实证明JPA无法表达这一点。 The solution was to rewrite in SQL. 解决方案是在SQL中重写。
I'm using QueryDSL to perform an aggregate query on a JPA data set for reporting. 我正在使用QueryDSL对JPA数据集执行聚合查询以进行报告。 I have no problem extracting the report data. 我没有问题提取报告数据。 For example: 例如:
...
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. 这将生成我的DTO对象列表,每个对象都包含车辆制造,车辆模型以及制作模型的车辆数量。 Like this: 像这样:
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? 有更好的吗?
This is not a QueryDSL limitation, but a JPA limitation. 这不是QueryDSL限制,而是JPA限制。 The solution was to rewrite in SQL. 解决方案是在SQL中重写。
你可以做query.select(q.field.countDistinct())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.