Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom expression in JPA CriteriaBuilder

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)
like image 297
Ivan Timoshin Avatar asked Aug 03 '16 12:08

Ivan Timoshin


People also ask

What is CriteriaBuilder in JPA?

CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings. See JavaDoc Reference Page... interface serves as the main factory of criteria queries and criteria query elements. It can be obtained either by the EntityManagerFactory. persistence.

What is CriteriaBuilder in hibernate?

public interface CriteriaBuilder. Used to construct criteria queries, compound selections, expressions, predicates, orderings. Note that Predicate is used instead of Expression<Boolean> in this API in order to work around the fact that Java generics are not compatible with varags. Since: Java Persistence 2.0.

Is Criteria API deprecated?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.

How do you write a criteria query?

The simplest example of a criteria query is one with no optional parameters or restrictions—the criteria query will simply return every object that corresponds to the class. Criteria crit = session. createCriteria(Product. class); List<Product> results = crit.


1 Answers

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"
    )
}
like image 149
singe3 Avatar answered Oct 10 '22 01:10

singe3