如何在查询复杂时查看spring数据jpa?

时间:2016-05-04 09:23:05

标签: spring-data-jpa

我有很多要导出的报告,数据是由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);
    }

1 个答案:

答案 0 :(得分:1)

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