【问题标题】:How to get json column as string in postgresql with jpa criteria builder?如何使用 jpa 标准构建器在 postgresql 中将 json 列作为字符串获取?
【发布时间】:2022-01-23 15:47:01
【问题描述】:

我在表中有一个 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 条件进行查询吗? 任何帮助将不胜感激。

【问题讨论】:

    标签: postgresql jpa criteria parseexception


    【解决方案1】:

    你可以试试这样的

    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

    【讨论】:

    • 首先,您评论的代码将与 json 对象完美配合,但我的是一个 json 数组。我已经更改了表格方案。我问的问题已经解决了。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2021-09-05
    • 1970-01-01
    • 2021-10-23
    • 2012-07-04
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多