JPA使用CriteriaQuery实现动态分组查询

JPA中实现动态分组查询,即输入几个筛选参数就按照几个参数进行分组查询,但是不知道输入的是几个参数,要实现动态的分组查询,用CriteriaQuery实现。

Repository:

java 复制代码
@Repository
public interface TestCostRepository extends JpaRepository<TestCost, Integer>, JpaSpecificationExecutor<TestCost> {
}

TestCostService:

java 复制代码
public interface TestCostService {
    List<Map<String,String>> dynamicGroupBy(List<String> groupByParams,String sumParam);
}

TestCostServiceImpl:

java 复制代码
@Service
public class TestCostServiceImpl implements TestCostService {

    @Autowired
    TestCostRepository repository;

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Override
    public List<Map<String, String>> dynamicGroupBy(List<String> groupByParams, String sumParam) {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
        Root<TestCost> root = query.from(TestCost.class);

        List<Expression<?>> expressions = new ArrayList<>();
        for (String field : groupByParams) {
            expressions.add(root.get(field));
        }
        query.groupBy(expressions.toArray(new Expression[0]));

        Expression<BigDecimal> sumExpression = cb.sum(root.get(sumParam));
        expressions.add(sumExpression);
        query.multiselect(expressions.toArray(new Expression[0]));

        TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
        List<Object[]> resultList = typedQuery.getResultList();

        List<Map<String, String>> returnList = new ArrayList<>();
        for (Object[] result : resultList) {
            Map<String, String> returnMap = new LinkedHashMap<>();
            returnMap.put("name", (String) result[0]);
            returnMap.put("gender", (String) result[1]);
            returnMap.put("cost", result[2].toString());
            returnList.add(returnMap);
        }

        return returnList;
    }

}
相关推荐
特立独行的猫A31 分钟前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java1 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang2 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio3 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易4 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊4 小时前
LeetCode3041~3060题目解析
java·leetcode
索西引擎4 小时前
MySQL 进阶:视图、存储过程、存储函数与触发器
数据库·mysql
文丑颜不良啊5 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean02235 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
bksczm6 小时前
InnoDB 通用表空间与临时表空间详解
大数据·数据库·mysql