Compare Date entities in JPA Criteria API

前端 未结 4 855
离开以前
离开以前 2020-12-03 00:20

Using JPA 2 with EclipseLink implementation.

I\'m trying to build a dynamic query which should bring me some records persisted after a given date.



        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 01:22

    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.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.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

提交回复
热议问题