最近开发中发现个问题:
hibernate下SQLQuery返回BigInteger而不是Long的问题
问题复现:
List<Long> masterIds = null;
try {
String sql = "select Fmasterid from t_room where Fname like '%" + roomName + "%'";
log.info("sql --> {}", sql);
//注:此处需要转一下 如果不转会出现bigint转换long错误
Query query = session.createSQLQuery(sql);
masterIds = query.list();
return masterIds;
} catch (Exception e) {
log.info("getMasterIdsByRoomName error={}",e,e);
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return null;
此处没问题,正常接收。。。。。
但是下方转换的时候问题来了,报错了
// 去重
Set<Long> matchSet = new HashSet<Long>();
//根据房间描述 查询 added by xzz 2018/11/09
List<Long> masterIds = roomService.getMasterIdsByRoomName(searchParam);
if (masterIds != null && masterIds .size() > 0) {
for (Long masterId : masterIds ) {
matchSet.add(masterId);
}
}
//end
去重的时候,定义一个Set<Long>,之后将上方获取的masterIds循环放入Set<Long>中报错
- java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
hibernate我本身就用的很少,所以没有深究,查了下资料解决方法如下:
session.createSQLQuery(sql).addScalar("Fmasterid",new LongType());
可以参考:https://blog.csdn.net/vacblog/article/details/7769976
此篇文章还有些其他的查询,可以一起看了
List<Long> masterIds = null;
try {
String sql = "select Fmasterid from t_room where Fname like '%" + roomName + "%'";
log.info("sql --> {}", sql);
//注:此处需要转一下 如果不转会出现bigint转换long错误
Query query = session.createSQLQuery(sql).addScalar("Fmasterid",new LongType());
masterIds = query.list();
return masterIds;
} catch (Exception e) {
log.info("getMasterIdsByRoomName error={}",e,e);
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return null;
遇到同样坑的小伙伴可以这样解决。。。