详解QueryDSL使用Group by查询,自定义返回对象

背景

使用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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

境里婆娑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值