代码之家  ›  专栏  ›  技术社区  ›  Kevin

使用nativeQuery在Hibernate中查询JSONB列

  •  0
  • Kevin  · 技术社区  · 2 年前

    我使用的是Hibernate 6.2.17、postgres和spring-boot 3.1.7。

    我有一个DB表,如下所示:

           Column        |          Type          | Collation | Nullable | Default 
    ---------------------+------------------------+-----------+----------+---------
     id                  | bigint                 |           | not null | 
     sd_id               | bigint                 |           | not null | 
     day                 | date                   |           | not null | 
     attributes          | jsonb                  |           |          | 
    

    我想通过表中各行的键聚合json对象中的值,并使用本机查询来实现这一点:

      @Query(
          nativeQuery = true,
          value =
              """
          SELECT sd_id AS sdId, json_object_agg(key, val) AS attributes
          FROM (
              SELECT sd_id, key, sum(value\\:\\:numeric) val
              FROM pr, jsonb_each_text(attributes)
              WHERE pr.day BETWEEN :startDay AND :endDay
              GROUP BY sd_id, key
          ) s
          GROUP BY sd_id
          """)
      List<PRCustomStatistics> getPRCustomStatistics(
          LocalDate startDay, LocalDate endDay);
    

    问题是,我唯一能做到这一点的方法就是使用这个DTO:

    public interface PRCustomStatistics {
      long getSdId();
      String getAttributes();
    }
    

    哪里 attributes 是 String ,而不是任何类型的JSON表示。例如 属性 可能具有值 '{"f1":10,"f2":20}' .

    我该怎么办才能回来 属性 作为一个 Map<String,Double> 或任何其他类型的结构化数据,而不是 一串 ?

    0 回复  |  直到 2 年前