旧的然后在java持久性中查询

时间:2012-05-29 12:42:26

标签: java hibernate persistence hql

我需要做一个查询,我会把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'";

是我试过的...... 任何甜蜜的帮手,提前谢谢: - )

编辑: 所以我改变了我的方法现在看起来像这样:

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)

2 个答案:

答案 0 :(得分:3)

SessionFactory sf = // get your session factory
Query q = sf.getCurrentSession()
        .createQuery(hqlQuery);
q.setParameter("minDate",minDate.getTime())
 .setParameter("app", appId)
 .list();

如果您设置了date参数,假设sent_date的类型是Notifications模型类中的Date。此外,在查询的这一部分select n from notifications上,请确保通知是您班级的实际名称。案件很重要!应该是select n from Notifications n

<强>更新

您需要声明该类的别名。

答案 1 :(得分:0)

如果我没弄错的话,当您在查询中添加日期时,不应该做这样的事情:

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'";

注意'围绕minDate变量