简体   繁体   English

动态 JPA 标准生成器

[英]Dynamic JPA criteria builder

I am using Spring boot JPA to below execute below query我正在使用 Spring 启动 JPA 到下面执行下面的查询

select DELTA_TYPE,OPERATION_ID,COUNT(*) from ACTIVE_DISCREPANCIES ad group by DELTA_TYPE,OPERATION_ID

DELTA_TYPE,OPERATION_ID, etc may come from external system, in repository class I tried to execute native query DELTA_TYPE、OPERATION_ID 等可能来自外部系统,在存储库 class 中我尝试执行本机查询

    @Query(value="select OPERATION_ID,DELTA_TYPE,count(*) from ACTIVE_DISCREPANCIES ad group by ?1",nativeQuery = true)
    public List<Object[]> groupByQuery(@Param("reconType") String recGroupColumns);

where recGroupColumns="DELTA_TYPE,OPERATION_ID" but didnt work as @param will split ','其中 recGroupColumns="DELTA_TYPE,OPERATION_ID" 但没有工作,因为@param 将拆分','

Second option for me was criteria query我的第二个选择是标准查询

public List<Object[]> getReconGroupList() {
        String recGroupColumns = "OPERATION_ID,DELTA_TYPE";
        String[] arrStr = recGroupColumns.split(",");
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
        Root<ActiveDiscrepancies> adr = query.from(ActiveDiscrepancies.class);
        query.groupBy(adr.get("operationId"), adr.get("deltaType"));

    // query.groupBy(adr.get("deltaType"));
    query.multiselect(adr.get("operationId"), adr.get("deltaType"), criteriaBuilder.count(adr));
    TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
    List<Object[]> resultList = typedQuery.getResultList();
    return resultList;
}

Here how can I pass groupBy and multiselect dynamically?在这里如何动态传递 groupBy 和多选?

Using projections we can solve this scenario, below is the code使用投影我们可以解决这种情况,下面是代码

     Criteria criteria = getSession().createCriteria(ActiveDiscrepancies.class);

      ProjectionList projectionList = Projections.projectionList();

      for(String str : colList) {
        projectionList.add(Projections.groupProperty(str));
      }
        projectionList.add(Projections.rowCount());
        criteria.setProjection(projectionList);
        List results = criteria.list();

        getSession().close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM