JPA中实现动态分组查询,即输入几个筛选参数就按照几个参数进行分组查询,但是不知道输入的是几个参数,要实现动态的分组查询,用CriteriaQuery实现。
Repository:
@Repository
public interface TestCostRepository extends JpaRepository<TestCost, Integer>, JpaSpecificationExecutor<TestCost> {
}
TestCostService:
public interface TestCostService {
List<Map<String,String>> dynamicGroupBy(List<String> groupByParams,String sumParam);
}
TestCostServiceImpl:
@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;
}
}