简体   繁体   中英

Some SQL functions don't work in HQL

The following sql is valid when I run it directly on PostgreSql as well as in HQL in Hibernate:

sql = "update Address set city = upper(city)"

HQL: session.createQuery(sql).executeUpdate()

However, when I try to use sql function left(String, number) as follows:

sql = "update Address set city = left(city,7)"

It runs fine directly on PostgreSql, but throw this exception in Hibernate:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: left near line 1

I have the dialect set correctly as:

props.put("hibernate.dialect", PostgreSQLDialect.class.getName());

How can I get HQL to behave the same as SQL?

Why does the "upper" function work, but not the "left" function?

HQL does support upper function, but it does not support left function. You have to use equivalent substring function that takes three arguments:

"update Address set city = substring(city,1,7)"

You can also compute the substring from the Java level, by creating query in this way:

"update Address set city = :city"

And then you can run query this way:

session.createQuery(sql).setParameter("city", newCity).executeUpdate();

Where city is a substring created like this:

  newCity = city.substring(1,7)

The easier (and less Hibernateish) way is to use creativeNativeQuery function instead of createQuery, you won't have to do any substring calculations this way. This runs the method just as if you were using your PostgreSQL syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM