【问题标题】:Search jsonb field using criteria API使用条件 API 搜索 jsonb 字段
【发布时间】:2020-04-09 19:22:55
【问题描述】:

我有一个实体,其中有一个 jsonb 类型的内容字段。复杂的 json 存储在该字段中。我需要在此字段上进行选择。我使用标准 API。这样的查询有效:

public Predicate getPredicate(){
        Expression<String> function = builder.function("jsonb_extract_path_text",
                String.class,
                root.<String>get("content"), 
                builder.literal("unit"),
                builder.literal("id")
        );
        return builder.like(
                function,
                "%" + value + "%"
        );
}

JSON 看起来像这样:

{
 "unit":{
   "id":"58bd51815744bf06e001b57b",
   "name":"my name",
   "another":{
     "anotherId":"45545454"
   }
 }
}

问题在于 JSON 的搜索条件可能完全不同。也许有搜索:unit.id = 58bd51815744bf06e001b57b。可能是这样的:unit.another.anotherId = 45545454。 甚至可能是这样:unit.id = 58bd51815744bf06e001b57b and unit.name = "my name"

我想我可以像这样解决我的问题:

Expression<String> function = builder.function("jsonb_extract_path_text",
        String.class,
        root.<String>get("content"),
        builder.literal("$.unit.id")
);

但由于某种原因,这不起作用。任何想法如何解决这个问题?

【问题讨论】:

    标签: java json postgresql hibernate criteria-api


    【解决方案1】:

    我找到了解决方案: 所以我使用 Spring 数据进行搜索

    EntityAbstract one = entityRepository.findOne(((Specification<EntityAbstract>)
            (root, query, builder) -> {
                Expression<?>[] expressions = {root.<String>get("content"), builder.literal("unit"), builder.literal("id")};
                return toPredicate(root, query, builder, projectionName, expressions);
            }
    )).orElseThrow(() -> new ResourceNotFoundException("Entity not found"));
    

    这就是使用 Criteria Builder 的方法的样子

    public Predicate toPredicate(Root<EntityAbstract> root, CriteriaQuery<?> query, CriteriaBuilder builder, String value, Expression<?>[] args) {
        Expression<String> function = builder.function("jsonb_extract_path_text",
                String.class, args
        );
        return builder.like(
                function,
                "%" + value + "%"
        );
    }
    

    也就是说,我需要形成一个想要长度的数组(表达式),这并不难

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-03
      • 2017-03-20
      • 2023-02-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2020-01-03
      相关资源
      最近更新 更多