postgresql - 如何使用 jpa 条件生成器在 postgresql 中将 json 列作为字符串获取?

标签 postgresql jpa criteria parseexception

我在表中有一个 json 列,例如:

    @Type(type = "jsonb")
    @Column(name = "json_data", columnDefinition = "json")
    private List<Persion> jsonData = Collections.emptyList();
    public class Persion implements Serializable {
        private String name;

        private int age;

        private String sex;
    }

我想查询在json中包含特定名称的行,我写了这段代码:

    predicates.add(
            criteriaBuilder.like(
                criteriaBuilder.treat(root.get("jsonData"), String.class),
                "%" + name + "%"
        )
    )

但它抛出异常:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('%' (code 37)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

能不能只把json读成字符串,然后用where条件查询? 任何帮助将不胜感激。

最佳答案

你可以试试这样的东西

predicates.add(
        criteriaBuilder.like(
            criteriaBuilder.function("jsonb_extract_path_text", 
             String.class, root.get("jsonData"), 
             criteriaBuilder.literal("name")), "%" + name+ "%"
    )
)

我发现这些链接非常有用 How do I use spring data jpa to query jsonb column? Build predicates for a postgres jsonb column with criteria builder using JPA criteria

关于postgresql - 如何使用 jpa 条件生成器在 postgresql 中将 json 列作为字符串获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70714742/

相关文章:

mysql - Rails Slow Postgres Query with Order using Index

sql - 如何计算 PostgreSQL 中列中的重复值?

java - EJB 项目中的 Jeddict

jpa - 抽象模式类型未知

excel - 具有两个标准的 MATCH 公式作为工作表函数 (VBA)

postgresql - 如何在postgresql中生成序列

sql - 查询滚动日期范围内不同值的计数

java - 如何使用 Criteria 查询将 String 字段转换为 where 子句中的数字?

grails - 实体之间的关系标准-Grails

java - 构建 CriteriaBuilder 查询来比较列表