我这是从Java应用程序是这样执行的查询:PostgreSQL的功能全面和JPA /休眠
Query query = getEntityManager().createQuery(hql);
查询看起来是这样的:
String hql = "select * from table a where round(column1, 3) = round(parameter, 3)";
这里column1
是Double
类型。它的价值就像143.02856666
。我需要保留原来的价值,但对于某些业务逻辑只需进行整理和比较即可。
配置的初始数据库是H2,这工作正常。现在数据库已经更改为Postgres,现在这个查询出错了。
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.
Postgres中的round()
函数接受一个数字数据类型并需要一个转换。
如果直接在Postgres控制台中执行,下面的查询可以正常工作。
select * from table a where round(cast(column1 as numeric), 3) = round(cast(parameter as numeric), 3);
同样从java应用程序出错。
java.lang.IllegalArgumentException: org.hibernate.QueryException: Could not resolve requested type for CAST : numeric
也试过Query query = getEntityManager().createNativeQuery(hql);
这将导致一个新的错误。
org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "where"
如果我调试,执行下面这行时出错。
List resultList = query.getResultList();
如何重写查询,以便它对付Postgres?
参数是一个实际参数,并且表中没有列吗?如果是这样,如果查询字符串从未被操纵过,你的查询将如何工作?另外我只用Eclipselink和Postgres测试了一个nativeQuery,它可以工作。我建议你总是把问题切成要点,并为这样的问题提供表格定义... –
谢谢,我的坏会保重。该参数将被传递给执行此查询的方法。它类似于:parmeter,并将使用.setParameter(“parameter”,parameterValue)传入; – VKC
我已通过将其转换为映射到数字的big_decimal来解决此问题。四舍五入(cast(column1作为数字),3)舍入(cast(column1作为big_decimal),3)。在控制台中启用show_sql显示此查询为round(cast(column1作为数字(19,2),3))任何指针,如果它可以以某种方式写入,以便将数字(19,2)转换为数字(19,6) ),因为这会给我更准确的结果。 – VKC