背景
使用group by对某一个字段分组,并统计此字段条数。
sql语句为:select count(1),字段 from table group by 字段
创建QueryDSL查询返回对象
public class TxnOutCollectReport{
@ExcelField(title = "输入来源",order = 1)
private String inputSource;
@ExcelField(title = "总数",order = 2)
private Long cnt;
public TxnOutCollectReport() {
}
public TxnOutCollectReport(String inputSource, Long cnt) {
this.inputSource = inputSource;
this.cnt = cnt;
}
public String getInputSource() {
return inputSource;
}
public void setInputSource(String inputSource) {
this.inputSource = inputSource;
}
public Long getCnt() {
return cnt;
}
public void setCnt(Long cnt) {
this.cnt = cnt;
}
}
使用QueryDSL查询
什么是Querydsl呢?Querydsl是一个框架,它可以通过它提供的的API帮助我们构建静态类型的SQL-like查询,也就是在上面我们提到的组织查询方式。可以通过诸如Querydsl之类的流畅API构造查询。
Querydsl是出于以类型安全的方式维护HQL查询的需要而诞生的。 HQL查询的增量构造需要String连接,这导致难以阅读的代码。通过纯字符串对域类型和属性的不安全引用是基于字符串的HQL构造的另一个问题。
随着域模型的不断变化,类型安全性在软件开发中带来了巨大的好处。域更改直接反映在查询中,而查询构造中的自动完成功能使查询构造更快,更安全。
使用QueryDSL查询核心代码:
要统计字段需要new出来
QTBankTxnOutGoing inputSource = new QTBankTxnOutGoing("inputSource");
自定义返回对象使用 Projections.constructor把需要返回的对象输入。
QTBankTxnOutGoing qTBankTxnOutGoing = QTBankTxnOutGoing.tBankTxnOutGoing;
QTBankTxnOutGoing inputSource = new QTBankTxnOutGoing("inputSource");
List<TxnOutCollectReport> list = new JPAQueryFactory(em).from(qTBankTxnOutGoing)
.select(Projections.constructor(TxnOutCollectReport.class, qTBankTxnOutGoing.inputSource, inputSource.count()))
.groupBy(qTBankTxnOutGoing.inputSource).fetch();
List<TxnOutCollectReport> list1 = new JPAQueryFactory(em).from(qTBankTxnOutGoing)
.select(Projections.constructor(TxnOutCollectReport.class, qTBankTxnOutGoing.inputSource, inputSource.count()))
.groupBy(qTBankTxnOutGoing.inputSource).fetch();