我需要查询 5 天前的数据。(自定义日期) 我看过 HQL,但由于它是持久性的,所以我无法根据 here 访问 setTimestamp
String hqlQuery;
Calendar minDate = Calendar.getInstance();
minDate.add(Calendar.DATE, -days);
hqlQuery = "select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'";
我是这样试的... 任何可爱的 helper ,提前致谢:-)
编辑: 所以我改变了我的方法,它现在看起来像这样:
public static List<Notification> findOlderThen(EntityManager em, Long app, int days) {
String hqlQuery;
Calendar minDate = Calendar.getInstance();
minDate.add(Calendar.DATE, -days);
hqlQuery = "select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'";
System.out.println(hqlQuery);
return em.createQuery(hqlQuery).setParameter("app", app).setParameter("minDate",minDate.getTime()).getResultList();
}
但它给出了这个错误:
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [select n from notifications where n.app_id=:app and ((n.sent_date<=:minDate) OR (n.sent_date is null)) and n.handled='N'], line 1, column 28: syntax error at [where].
Internal Exception: UnwantedTokenException(found=where, expected 80)
最佳答案
SessionFactory sf = // get your session factory
Query q = sf.getCurrentSession()
.createQuery(hqlQuery);
q.setParameter("minDate",minDate.getTime())
.setParameter("app", appId)
.list();
将是如何设置日期参数,假设 sent_date 的类型是通知模型类中的日期。此外,在查询的这一部分 select n from notifications
中,确保 notifications 是您的类的实际名称。案例很重要!它可能应该是 select n from Notifications n
。
更新:
您需要声明类的别名。
关于java - 在 Java 持久性中较旧的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10799382/