Compare Date entities in JPA Criteria API

The problem is that with the string-based API it cannot infer the type for the result value of the get-Operation. This is explained for example in Javadoc for Path.

If you use

predicates.add(builder.lessThanOrEqualTo(root.<Date>get("dateCreated"), param));

instead, it will work fine, because it can figure out the return type from the type argument and will find out that it is comparable. Note, the use of a parameterised method invocation root.<Date>get(...) (see, e.g., When is a parameterized method call useful?).

Another (in my opinion better) solution is to use the metamodel based API instead of the string-based one. A simple example about canonical metamodel is given for example here. If you have more time to invest, this is a good article about static metamodel: Dynamic, typesafe queries in JPA 2.0

Leave a Comment

techhipbettruvabetnorabahisbahis forumu