【问题标题】:HQL where clause with variable inserted插入变量的 HQL where 子句
【发布时间】:2015-03-31 16:23:51
【问题描述】:

我需要在现有的 HQL where 子句中插入一个变量,如下所示:

java.sql.Timestamp currentDate = new Timestamp(System.currentTimeMillis());

Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= " + currentDate + " and a.endDate <= " + currentDate);

执行上述操作时,我收到以下错误消息:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 18 near line 1, column 79 
        [from gov.va.med.domain.fee.AdjustmentReason a where a.startDate >= 1969-12-31 18:00:00.0 and a.endDate <= 1969-12-31 18:00:00.0]

我是否应该在现有的 AdjustmentReason 模型类中添加一个 currentDate 字段,即使它不在数据库中以使这更简单?

非常感谢任何帮助!

【问题讨论】:

  • 提示:对于日期,您可以使用BETWEEN 子句,例如。 SELECT a FROM entity WHERE startDate BETWEEN :startDate AND :endDate

标签: java oracle hibernate toad


【解决方案1】:

当您创建Query 对象时,您应该使用setParameter 来设置查询中的日期,例如。

 Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= :0 and a.endDate <= :1");
q.setParameter(0,dateFrom);
q.setParameter(1,dateFrom);

这就是准备好的语句的原因。 完整的例子可以找到here

【讨论】:

    【解决方案2】:

    这种方式不是最好的方式,它使你的代码容易受到 SQL 注入的影响,正确的做法和解决问题的方法如下:

     Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= :startDate and a.endDate <= :endDate")
    .setParameter("starDate", currentDate)
    .setParameter("endDate", currentDate)
    

    希望对你有帮助!

    【讨论】:

    • 欢迎您!请接受答案,以便有相同问题的其他人可以更轻松地看到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多