javapostgresqlhibernatejpahibernate-criteria

How to write hibernate criteria logic for Postgres json cast query?


In my Postgres database, I have a column of character_varying data type where data is stored in json. Now I want to retrieve some information from table where I want to check some condition in this column in "where" clause. Query is something like this : - select cl1, cl2, from table_name where cond1 and cond2 and cond3. Consider cond3 is something like this

" column_name :: jsonb ->> 'property_name' <> '["some value"]' ".

Now I want to build criteria for this, In application entity type for this column is of Json_Node datatype. Now How should I build the criteria for this particular expression ?

I have already written the criteria till cond2 , but stuck with cond3.

Suggestions will be helpful

  1. I have tried adding this query part(column_name:: jsonb ->> 'property_name') in Criteriabuilder literal part.
  2. Then I am comparing with criteria builder not equal method

Solution

  • There are couple of ways we can tackle this problem.

    1. Using available JSON type conversion
    2. Creating Custom Postgres function in DB and making use of that

    So, to explain, I was facing some challenges to build a criteria logic to filter some data from Postgres database column, it was bit complicated because column was of type character_varying and it has the JSON data inside it.

    When we cast the character_varying column to JSON, we can make use of in build JSON functions as well.

    Using casting in SQL query is straight forward, we can use either :: operator or CAST function of POstgresSQL.

    But building criteria gets complicated if we want to use above mentioned approaches for casting, we can't make use of Criteria builder library's function method, so that we can pass the actual function name and arguments inside it. For example,

    (cb.function("function name", type.class, arg1))
    

    Using Criteria builder literal methods did not provided with satisfactory results. Passing part of query as binding parameter.

    To conclude PostgreSQL have another option to cast. With this we can use it as function and cast and further filter our data.

    JSON(column_name)
    

    Building criteria is also possible with JSON, as it is treated as function.

    As mentioned, another approach is creating a custom function which does the casting job using operator or CAST function and using this custom function while building the criteria.