【问题标题】:PSQL/JPA: rewrite query from returning List<> of occurences to Map<Date, List<>> of Ocurrences per DatePSQL/JPA:从返回 List<> 到 Map<Date, List<>> of Occurrences per Date 重写查询
【发布时间】:2017-07-15 06:32:45
【问题描述】:

我有一个预定义的查询/jpa 操作

jpaOperations.findByQuery(ActivityCountByCategory.class,
"SELECT NEW ActivityCountByCategory(u.text, count(1)) 
FROM Activity a JOIN a.groupCategories c, UserDefinedCode u 
WHERE (u.id.code = c AND u.id.entityName='AKTOR_AKTIVITET' AND u.id.fieldName='KATEGORI') 
AND a.closedIndicator = 'F' GROUP BY u.text, u.lineNo ORDER BY u.lineNo");

返回一个名为ActivityCountByCategory 的DTO 列表,其中包含一个活动的名称和一个代表数据库中出现次数的数字。 因此,此方法返回所有时间的单个活动的数量。

UserDefinedCode

表的定义使得活动驻留在AKTOR_AKTIVITET 中并具有从UserDefinedCode 表示的第二个表引用的ID,以便名称 - 部分与活动分离。

我需要扩展此查询,以便我可以传递 Date fromDate 和 Date toDate 并让它返回某种形式的 List&lt;Object[]&gt;Map&lt;Date, List&lt;ActivityCountByCategory&gt;&gt; 这样我就可以将出现的事件拆分为单独的日期between fromDate and toDate 并将每个返回列表映射到一个特定的日期。

【问题讨论】:

    标签: java sql hibernate jpa jpql


    【解决方案1】:

    我用原生 SQL 重写了查询,并编辑了 DTO 以解释 Date,然后在支持 bean java 代码中进行了一些解析:

    public List<ActivityCountByCategory> getCreatedUserDefinedActivityCountByDate(Date fromDate, Date toDate) {
    
            Query query;
            query = entityManager.createNativeQuery("SELECT" +
                    " trunc(a.dato), fcode.TEXT, COUNT(1) FROM ACTIVITY a INNER JOIN ACTIVITY_CATEGORY act_cat ON a.ID=act_cat.ACTOR_ID INNER JOIN " +
                    "user_defined_code fcode ON fcode.kode = act_cat.category where ... " + 
                    "AND trunc(a.DATO) BETWEEN :fromDate AND :toDate GROUP BY trunc(a.dato), fcode.TEXT , fcode.lineNo ORDER BY fcode.lineNo ");
            query.setParameter("fromDate", fromDate);
            query.setParameter("toDate", toDate);
    
            List<Object[]> resultList = query.getResultList();
            List<ActivityCountByCategory> list = new ArrayList<>();
            for (Object[] result : resultList) {
                list.add(new ActivityCountByCategory((String) result[1], (Number) result[2], (Date) result[0]));
            }
            return list;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-27
      • 2017-03-02
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多