比较JPA条件API中的日期实体 [英] Compare Date entities in JPA Criteria API
问题描述
使用JPA 2与EclipseLink实现。
我正在尝试构建一个动态查询,这应该会使我在一个给定日期。
I'm trying to build a dynamic query which should bring me some records persisted after a given date.
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Event> criteria = builder.createQuery(Event.class);
Root<Event> root = criteria.from(Event.class);
criteria.select(root);
criteria.distinct(true);
List<Predicate> predicates = new ArrayList<Predicate>();
//...
if (dateLimit != null){
ParameterExpression<Date> param = builder.parameter(Date.class, "dateLimit");
predicates.add(builder.lessThanOrEqualTo(root.get("dateCreated"), param));
}
lessThanOrEqualTo()
和 le()
是API中唯一可以帮助我的两种方法。这个警告是由eclipse抛出的:
lessThanOrEqualTo()
and le()
are the only two methods in the API which look like may help me in this case. This warning is thrown by the eclipse though:
Bound mismatch: The generic method lessThanOrEqualTo(Expression<? extends Y>, Expression<? extends Y>)
of type CriteriaBuilder is not applicable for the arguments (Path<Object>, ParameterExpression<Date>).
The inferred type Object is not a valid substitute for the bounded parameter
<Y extends Comparable<? super Y>>
我可以想像,我没有采取正确的方法来解决这个问题,但我找不到任何一个可能的解决方案的提示或指针。
I can imagine that I'm not taking the correct approach for this problem but I can't find anywhere some tips or pointers for a possible solution.
推荐答案
问题是,使用基于字符串的API,它不能推断类型对于获取
-Operation的结果值。这在例如
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.
如果您使用
predicates.add(builder.lessThanOrEqualTo(root.<Date>get("dateCreated"), param));
相反,它可以正常工作,因为它可以从类型参数中找出返回类型,发现它是可比的。注意,使用参数化方法调用 root。< Date> get(...)
(参见,例如,什么时候参数化方法调用有用?)。
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?).
另一个(在我看来更好)的解决方案是使用基于元模型的API而不是基于字符串的API。给出了一个关于规范元模型的简单示例,例如这里。如果您有更多的时间投资,这是关于静态元模型的好文章:动态,JPA 2.0中的类型安全查询
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
这篇关于比较JPA条件API中的日期实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!