我在表中有一个 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/