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个uses中可以看到的(:id and :days)。
:id and :days
但是,当我使用now():: date语句时,它是特定的postgreSQL语法,因此hibernate会破坏所有内容。
由于你使用的是Postgres,因此我将完全更改date():
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();
我只是遇到了这个问题,不得不使用强制转换,所以我尝试了一些方法使其正常工作。原来你逃脱了:在hibernate中\
\
但是,在Java中,要\开始打印,必须使用对其进行转义\。 因此,如果你想:在SQLhibernate查询中放入a ,则必须将其编写为:\\:
:
\\
而且,例如在我的情况下,如果要在PostgreSQL中进行强制转换,则必须这样做:field\\:\\:int如果要将某些字段强制转换为整数。
field\\:\\:int