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

141 Views Asked by At

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.

2

There are 2 best solutions below

5
Stephen C On BEST ANSWER

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.

0
Bhawana Solanki On

GreaterThan or gt or LessThan or lt expects either (Expression<? extends Y> x,Y y) or (Expression<? extends Y> x, Expression<? extends Y> y).

So particularly when two integers are to be compared either of input to these criteriaBuilder method has to be a expression whose Object is same as the object of other input. Below is the code which worked for me:

Expression<Integer> expr1 = 
criteriaBuilder.selectCase(root.get("amt"))
.when(1,10) /* this could be your any business logic, it is what myFunc was doing */
.when(2,20).as(Integer.class);
Integer expr2 = 15;
Predicate predicates = criteriaBuilder.lessThan(expr1,expr2);