【问题标题】:How to query jsonb column using spring data specification?如何使用spring数据规范查询jsonb列?
【发布时间】:2019-09-28 00:59:28
【问题描述】:

我有下表temp_tbl(postgres):

    ID(int)     NAME(TEXT)    LINKS(jsonb)
    --------    ----------    -------------------
    1           Name1         ["1","23","3", "32]
    2           Name2         ["11","3","31", "2]
    3           Name3         ["21","13","3", "12]

现在我的本机查询来获取“LINKS”值为“3”的行是:

    select * from temp_tbl where links @> '["3"]'

返回第 2 行和第 3 行。

我想使用 org.springframework.data.jpa.domain.Specification 实现这个查询

我已经实现了类似下面的内容,其中 jsonb 列不是数组,但使用 jsonb_extract_path_text 具有键值 json。但是上面的列只存储数组中的值。

我的实体类。

@Entity
@Table(name = "temp_tbl")
public class TempTbl {
  @Id
  @Column(name = "ID")
  private Long id;

  @Column(name = "NAME", nullable = false)
  private String name;

  @Column(name = "LINKS", columnDefinition = "jsonb null")
  @Convert(converter = JsonbConverter.class)
  private List<String> linkIds;
}

在使用标准构建器将上述查询转换为规范时,我需要帮助。

【问题讨论】:

    标签: spring-data criteria


    【解决方案1】:

    使用Jpa规范检查jsonb数组是否包含String的一种方法是使用函数jsonb_containsjsonb_build_array,后者用于将String更改为jsonb数组以供jsonb_contains使用.

        public static Specification<TempTbl> linkInLinks(String linkId) {
            return (root, query, builder) -> {
                Expression toJsonbArray = builder.function("jsonb_build_array", String.class, builder.literal(linkId));
                return builder.equal(builder.function("jsonb_contains", String.class, root.get("linkIds"), toJsonbArray), true);
            };
        }
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2018-05-31
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多