How to do a timestamp comparison with JPA query?

浪子不回头ぞ 提交于 2019-12-04 03:32:33
DataNucleus

So the query you input is not JPQL (which you could see by referring to the JPA spec). If you want to compare a field with a Date then you input the Date as a parameter to the query

msg.targetTime < CURRENT_TIMESTAMP AND msg.targetTime > :param

THIS IS NOT SQL.

The JDBC escape syntax may not be supported in the version of OpenJPA that you're using. The documentation for the latest 1.2.x release is here: http://openjpa.apache.org/builds/1.2.2/apache-openjpa-1.2.2/docs/manual/manual.html#jpa_langref_lit .

The documentation mentioned earlier refers to the docs for OpenJPA 2.0.0 (latest): http://openjpa.apache.org/builds/latest/docs/manual/jpa_langref.html#jpa_langref_lit

That said is there any reason why you want to inject a string into your JPQL? What about something like the following snippet?

Date now = new Date();
Date thirtyDaysAgo = new Date(now.getTime() - (30 * MS_IN_DAY));

Query q = em.createQuery("Select m from Message m " 
    + "where m.targetTime < :now and m.targetTime > :thirtyDays");
q.setParameter("now", now); 
q.setParameter("thirtyDays", thirtyDaysAgo);

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