javajpacriteria

CriteriaBuilder Cannot resolve method 'greaterThan(int, int)'


I'm forming a query where I'm comparing the db result with API request data, but i'm getting below error:

Cannot resolve method 'greaterThan(int, int)'.

My code looks something like below. 2 is coming from the API request.

List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.greaterThan(myFunc(root.get("amt")),2));

Basically myFunc function would multiply root.get("amt") with some number based on some condition. but this is not working for me as both expressions are of type "int" and it does not expect that. How to form specification in this kind of scenario.


Solution

  • The signature for greaterThan is:

    <Y extends Comparable<? super Y>> Predicate 
    greaterThan(Expression<? extends Y> x, Expression<? extends Y> y)
    

    In other words, it takes arguments that are Expression objects whose value type (Y) implements Comparable<? extends Y>. Java doesn't know how to convert two integers into two Expression objects. (In fact, I can't think of any PL that would be able to do that conversion without you saying what kind of Expression you need there.)

    However, if you look at the javadoc for CriteriaBuilder you will also see some gt methods that create Predicate objects to compare Number instances. So the following ought to work:

    predicates.add(
        criteriaBuilder.gt(
            Integer.valueOf(myFunc(root.get("amt"))),
            Integer.valueOf(2)));
    

    CORRECTION

    predicates.add(
        criteriaBuilder.gt(
            criteriaBuilder.literal(
                Integer.valueOf(myFunc(root.get("amt")))),
            Integer.valueOf(2)));
    

    because the first argument of gt needs to be an expression too.