Using Hibernate query : colon gets treated as para

2020-01-31 02:59发布

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();

getting error:

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

How can I use this syntax in HQL?

Basically the problem is that I want to use colon(:) in my query, but when hibernate sees colon, it thinks that it is a paramter(:parameterName is syntax for parameters in HQL), as you can see from my 2 uses(:id and :days).

But when I am using now()::date statement, it is specific postgreSQL syntax, hibernate ruins everything.

6条回答
别忘想泡老子
2楼-- · 2020-01-31 03:15

Since you're on Postgres, I would change the date() completely:

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();

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

查看更多
走好不送
3楼-- · 2020-01-31 03:16

I just had this problem, had to use casts, so I tried some stuff to make it work. Turns out you escape : in hibernate with \

However, in java, to print \ to begin with, you have to escape it with \.
So, if you want to put a : in your SQL hibernate query, you have to write it like: \\:

And if you wanted to cast in PostgreSQL, such as in my case, you would have to, for example: field\\:\\:int if you wanted to cast some field as an integer.

查看更多
Ridiculous、
4楼-- · 2020-01-31 03:22

Take a look at http://www.postgresql.org/docs/8.1/static/sql-createcast.html

Try using cast. To me it worked like a charm.

查看更多
疯言疯语
5楼-- · 2020-01-31 03:25

You escape : with ::. I think.

Or try a nativequery

查看更多
爷的心禁止访问
6楼-- · 2020-01-31 03:40
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();
查看更多
在下西门庆
7楼-- · 2020-01-31 03:40

Named parameters take a colon ':' like this Is that what you were looking for ?

查看更多
登录 后发表回答