Select MAX timestamp with JPA2 Criteria API

岁酱吖の 提交于 2019-12-20 16:23:16

问题


So my entity has:

@Column(name="TS", nullable=false)
private java.sql.Timestamp timestamp; 

My generated MetaModel has:

public static volatile SingularAttribute<MyEntity,Timestamp> timestamp;

I want to select by the Max Timestamp value:

Root<MyEntity> root = query.from(MyEntity.class);
Expression maxExpression = cb.max(root.get(MyEntity_.timestamp));

But I am not allowed because:

max(Expression<N> x) Create an aggregate expression applying the numerical max operation. <N extends java.lang.Number> Expression

Of course Timestamp does not extend Number.

How can I do a MAX on a Timestamp column using the typesafe Criteria API ?


回答1:


Instead of max one should use CriteriaBuilder.greatest for Timestamp (and for Date, String and other Comparables as well). And if you ever need MIN for Timestamp, then use least method instead

Similar kind of issue can be be faced with less/greater/equal comparisons. Firs one accepts argument that extends Number, second one is for other comparables:

  • lt vs. lessThan
  • le vs. lessThanOrEqualTo
  • ge vs. greaterThanOrEqualTo
  • gt vs. greaterThan


来源:https://stackoverflow.com/questions/9616390/select-max-timestamp-with-jpa2-criteria-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!