JPQL子查询

开发涉及到JPQL子查询,网上找半天资料没找着,自己动手实验了一波,如下,为老系统的sql查询,是用mybatis实现的。系统重构技术选型spring data jpa,没有好的实现方法,所以仍然采用老系统的查询逻辑。老系统的查询逻辑如下所示:

选出每种类型中时间最大的那条数据

子查询示例

解决方案为:

    public Page<ContractInterBaseRate> findcontraceQuery(Pageable pageable, ContractInterBaseRateDTO cibr) {
        QContractInterBaseRate qcontracr = QContractInterBaseRate.contractInterBaseRate;
        QContractInterBaseRate q = new QContractInterBaseRate("temp");
        // 利率管理信息查询
        JPQLQuery<ContractInterBaseRate> query = this.repository.createDslQuery().select(qcontracr).from(qcontracr);
        BooleanExpression exp = qcontracr.id.goe(0);
        // 最新/历史(根据老系统查询方式查询)
        if (StringUtils.isNotBlank(cibr.getNewOrHistory())) {
            this.repository.createDslQuery().select(q.executeStartDate).from(q);
            exp = exp.and(qcontracr.executeStartDate.eq(this.repository.createDslQuery().select(q.executeStartDate.max())
                    .from(q).where(q.interestRateTypeCd.eq(qcontracr.interestRateTypeCd))));
        }
        final JPQLQuery<ContractInterBaseRate> countQuery = query.where(exp);;
        JPQLQuery<ContractInterBaseRate> queryResult = this.repository.getQuerydsl(ContractInterBaseRate.class)
                .applyPagination(pageable, countQuery);
        List<ContractInterBaseRate> contractList = queryResult.fetch();
        Page<ContractInterBaseRate> contracrPage = PageableExecutionUtils.getPage(contractList, pageable, () ->  countQuery.fetchCount());
        return contracrPage;
    }

遇到的问题为:

  • 1、构造Q对象的时候,不能用QContractInterBaseRate qcontracr = QContractInterBaseRate.contractInterBaseRate;
    QContractInterBaseRate q = QContractInterBaseRate.contractInterBaseRate;
    因为QContractInterBaseRate中contractInterBaseRate属性是static final的,如果都直接获取的话,子查询里边的(q.interestRateTypeCd.eq(qcontracr.interestRateTypeCd)会变成自己关联自己,有问题
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值