使用Hibernate查询:冒号被视为参数/转义冒号

return sessionFactory.getCurrentSession(). createQuery("FROM Weather WHERE city_id = :id AND date " + "BETWEEN now()::date AND now()::date + (:days - 1)"). setInteger("id", city_id).setString("days", days).list(); 

得到错误:

 org.hibernate.hql.ast.QuerySyntaxException: unexpected token: : 

如何在HQL中使用此语法?

基本上问题是我想在我的查询中使用冒号(:),但是当hibernate看到冒号时,它认为它是一个参数(:parameterName是HQL中参数的语法),正如你从我的2次使用中看到的那样( :id and :days )。

但是当我使用now():: date语句时,它是特定的postgreSQL语法,hibernate破坏了一切。

因为你在Postgres,我会完全改变日期():

 return sessionFactory.getCurrentSession(). createQuery("FROM Weather WHERE city_id = :id AND date " + "BETWEEN current_date AND (current_date + (integer :days - 1))"). setInteger("id", city_id).setString("days", days).list(); 

见http://www.postgresql.org/docs/8.2/static/functions-datetime.html

我刚遇到这个问题,不得不使用强制转换,所以我尝试了一些东西让它工作。 原来你逃脱:在冬眠中用\

但是,在java中,要打印\开始,你必须用\来转义它。
所以,如果你想在你的SQL hibernate查询中放一个:你必须把它写成: \\:

如果你想在PostgreSQL中进行转换,例如在我的情况下,你必须,例如: field\\:\\:int如果你想将一些字段转换为整数。

请查看http://www.postgresql.org/docs/8.1/static/sql-createcast.html

尝试使用演员。 对我而言,它就像一个魅力。

 return sessionFactory.getCurrentSession(). createQuery("FROM Weather WHERE city_id = :id AND date " + "BETWEEN cast(now() as date) AND cast(now() as date) + (:days - 1)"). setInteger("id", city_id).setString("days", days).list(); 

命名参数采用冒号’:’像这样你正在寻找什么?

你逃避::: 。 我认为。

或尝试本地查询