问题
I have a query which is executed from java application like this:
Query query = getEntityManager().createQuery(hql);
The query looks like this:
String hql = "select * from table a where round(column1, 3) = round(parameter, 3)";
Here column1
is of type Double
. The value it holds is like 143.02856666
. I need to retain the value as it is, but for some business logic just need to round and compare.
The initial database configured was H2 and this worked fine. Now the database has been changed to Postgres and this query now errors out.
ERROR: function round(double precision, integer) does not exist Hint: No function matches the given name and argument types. You might need to add explicit type casts.
The round()
function in Postgres takes a numeric datatype and needs a cast.
The below query works fine if executed directly in Postgres console.
select * from table a where round(cast(column1 as numeric), 3) = round(cast(parameter as numeric), 3);
The same from java application errors out.
java.lang.IllegalArgumentException: org.hibernate.QueryException: Could not resolve requested type for CAST : numeric
Also tried Query query = getEntityManager().createNativeQuery(hql);
This results in a new error.
org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "where"
If I debug, this errors out when the below line is executed.
List resultList = query.getResultList();
How do I rewrite the query so that it works against Postgres ?
回答1:
What you are doing with Query query = getEntityManager().createQuery(hql);
is calling a jpql
-query, which does not support all db-functions like round(v numeric, s integer)
.
Two Suggestions:
- Use
BETWEEN
and maintain jpql-mapping - Write a NativeQuery ->
Query query = em.createNativeQuery(queryString);
Your queryString
just has to be altered by your parameters.
来源:https://stackoverflow.com/questions/37759993/postgresql-function-round-and-jpa-hibernate