5

I have an Entity with a String field (storing JSON), and need to compare value from its database column with another value. Problem is that type of this database column is TEXT, but in fact it contains JSON. So, is there a way to write something like this? I.e. I need to compare my value with some field of JSON from TEXT column.

criteriaBuilder.equal(root.get("json_column").customExpressionn(new Expression{
   Object handle(Object data){
    return ((Object)data).get("json_field")
}
}), value)
7
  • use CAST? use FUNCTION? Aug 3, 2016 at 12:45
  • @NeilStockton, do you mean call sql function, that parses JSON and return my field? I hoped to find some CriteriaAPI solution. Aug 3, 2016 at 13:10
  • @NeilStockton, my entity? How can it help? My entity just have String field, which contains JSON. Aug 3, 2016 at 13:39
  • I've no idea what you're trying to achieve then. You have a String field storing a String value, stored in a TEXT column, and want to compare it to some value. You don't need any custom handler for that, just do "equal()". If you are instead wanting to compare some part of the text string ... then you give an example of the text string that is in the datastore and what part you want to compare with Aug 3, 2016 at 13:59
  • @NeilStockton, here is an example of this string: "{field1: \"value\",field2: \"value2\"}". I need to compare some my string with value of field2. Aug 3, 2016 at 14:53

1 Answer 1

7

Assuming, you have a MySQL server with version > 5.7.x

I just had the same issue. I wanted to find all entities of a class that had a JSON field value inside a JSON object column.

The solution that worked for me was something along the lines (sorry typing from a phone)

(root, query, builder)->{
    return builder.equal(
        builder.function("JSON_EXTRACT", String.class, root.get("myEntityJsonAttribute"), builder.literal("$.json.path.to.json.field")),
        "searchedValueInJsonFieldOfJsonAttribute"
    )
}
1
  • Hi , Found your post quite useful , can you please help me building the following query with criteria , like you shared above? SELECT * FROM audit_log WHERE JSON_CONTAINS_PATH(myEntityJsonAttribute 'one', "$.json.path.to.json.field"); Oct 5, 2017 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.