查询复杂时如何转义spring数据jpa?

how to enscape spring data jpa when the query is complex?

我有很多报告要导出,数据是通过spring数据jpa查询的,但是我编码的时候,很恶心。 一些代码:

public Object getReportBySupplier(ReportSupplierSearch reportSearch) {
        // 查询统计数据
        StringBuffer sql = new StringBuffer("SELECT ifnull(sum(apply_money), 0) money_count, count(1) itemCount FROM cash WHERE confirm_status = 2 ");
        sql.append("and supplier_id = " + reportSearch.getSupplierId());
        String start = null;
        String end = null;
        if (!StringUtils.isEmpty(reportSearch.getStime())) {
            start = reportSearch.getStime() + " 00:00:00";
            sql.append(" and paying_time >= " + "'" + start + "'");
        }
        if (!StringUtils.isEmpty(reportSearch.getEtime())) {
            end = reportSearch.getEtime() + " 23:59:59";
            sql.append(" and paying_time <= " + "'" + end + "'");
        }
        sql.append(" UNION ALL");
        sql.append(" SELECT ifnull((sum(t1.pay_money)), 0) money_count, count(1) itemCount FROM pay_info t1 ");
        sql.append(" where t1.supplier_id =" + reportSearch.getSupplierId());
        if (!StringUtils.isEmpty(reportSearch.getStime())) {
            sql.append(" and pay_time >= " + "'" + start + "'");
        }
        if (!StringUtils.isEmpty(reportSearch.getEtime())) {
            sql.append(" and pay_time <= " + "'" + end + "'");
        }
        Query query = em.createNativeQuery(sql.toString());
        List result = query.getResultList();
        return assembleReportBean(result);
    }

使用@query 注释或queryexecuterdsl。 这将帮助您以可管理的形式创建查询。