【问题标题】:Older then query in java persistence在 java 持久性中较旧的查询
【发布时间】:2012-05-29 12:42:25
【问题描述】:

我需要查询 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)

【问题讨论】:

  • 所以....当您尝试此操作时遇到异常?
  • 不能试,不能给查询加日期,至少不知道怎么弄。
  • 你需要声明一个别名。 select n from notifications n where...

标签: java hibernate persistence hql


【解决方案1】:
SessionFactory sf = // get your session factory
Query q = sf.getCurrentSession()
        .createQuery(hqlQuery);
q.setParameter("minDate",minDate.getTime())
 .setParameter("app", appId)
 .list();

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

更新:

您需要为该类声明别名。

【讨论】:

    【解决方案2】:

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

    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 变量周围的 '

    【讨论】:

    • 你不应该这样做,hibernate应该自动识别sent_date是一个日期并为你转义值。
    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多