5

I have a json column in table like:

 @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;
 }

And I want to query rows contains specific name in json, I have write this code:

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

But it throws exception:

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

Can I just read json as string and then use where condition to query? Any help would be appreciate.

MWiesner
9,07612 gold badges40 silver badges72 bronze badges
asked Jan 14, 2022 at 17:57
1
  • Hi Harry, I read in the comments that you solved the problem. Can you help me, I have the same problem. Commented Oct 23, 2022 at 7:54

1 Answer 1

2

You can try something like this

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

I have found these links very helpful How do I use spring data jpa to query jsonb column? Build predicates for a postgres jsonb column with criteria builder using JPA criteria

answered Jan 19, 2022 at 15:30
Sign up to request clarification or add additional context in comments.

1 Comment

thx first, The code you comment would work perfectly with json object, but mine is a json array. I alread change the table scheme. The question I asked was resolved. Thanks again.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.