我将所有sql查询转换为使用Hibernate参数。现在,当我在查询中添加一个参数并用变量映射它时,它总是给我错误:
错误o.h.e.jdbc.spi.SqlExceptionHelper - 转换数据类型时出错 nvarchar到bigint。
它没有任何意义,因为我添加了一个字符串参数。
查询如下:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid WHERE itemid IN ( :items ) "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= Cast( :endDate AS DATE) "
+ "GROUP BY o.materialrequireddate, itemid")
.setString("items", items).setString("endDate", endDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
当我返回原始工作查询时,它看起来像:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r " + "JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid " + "WHERE itemid IN (" + items + ") "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= Cast('" + endDate + "' AS DATE) "
+ "GROUP BY o.materialrequireddate, itemid");
使用命名参数时可以创建此异常的内容是什么?我使用的是Hibernate 5.1和数据库MS SQL服务器。
答案 0 :(得分:1)
我将查询更改为不转换为日期,并使用正确的类型设置参数:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid WHERE itemid IN ( :items ) "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= :endDate "
+ "GROUP BY o.materialrequireddate, itemid").setParameterList("items", items.stream().map(Item::getId).collect(Collectors.toList()))
.setDate("endDate", Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));