java - 使用条件 API 搜索 jsonb 字段

标签 java json postgresql hibernate criteria-api

我有一个实体,其中有一个 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 = 58bd51815744bf06e001b57bunit.name =“我的名字”

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

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

但由于某种原因这不起作用。有什么想法可以解决这个问题吗?

最佳答案

我找到了解决办法: 所以我使用 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 + "%"
    );
}

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

关于java - 使用条件 API 搜索 jsonb 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59371719/

相关文章:

php - 如何将json数组数据插入mysql?

json - 如何从swift调用rest web服务

sql - pgp_sym_encrypt 和解密 postgresql 中的整个列

java - 在实例化期间将值传递给对象时我缺少什么?

javascript - 如何给jsp中的函数提供路径

javascript - jQuery 动态从 JSON 文件获取数据

postgresql - 无法授予在架构上创建 View

c - 这个 Makefile 有什么问题? (找不到头文件)

java - 如何在 Mac 版本的 MatLab 中使用命令 xlswrite?

java - webapps 未获取 tomcat 7 conf/web.xml 自定义错误页面