在使用hibernate 调用原生sql 渴望查询出List<Long>类型数据,查询复制没报错,在使用List<Long>时,却报java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long 错误;
原来hq1查询出的Long 类型数据,sql查询出都是BigInteger 类型;
List a = new ArrayList<BigIneteger> ,在a 没用使用类型限定的情况下,可以赋值给任意类型的List,
如List<Long>,而把它当Long类型使用时,会出错
@Test
public void testc(){
List<Long> LongList = new ArrayList<Long>();
List bigIntList = new ArrayList<BigInteger>();
bigIntList.add(new BigInteger("1"));
LongList = bigIntList;
for(int i = 0; i < bigIntList.size();i ++ ){
if( bigIntList.get(i) instanceof Long){
System.err.println("is Long type");
}else{
System.err.println("is not Long type");
}
if( LongList.get(i) instanceof Long){
System.err.println("is Long type");
}else{
System.err.println("is not Long type");
}
if( bigIntList.get(i) instanceof BigInteger){
System.err.println("is BigInteger type");
}else{
System.err.println("is not BigInteger type");
}
try{
for(Long l : LongList){
System.err.println(l);
}
}catch(Throwable t){
t.printStackTrace();
}
}
}
//输出结果
is not Long type
is not Long type
is BigInteger type
java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
本文探讨了在使用Hibernate框架执行原生SQL查询时,返回的数据类型与预期不符的问题。具体表现为查询结果为BigInteger类型而非期望的Long类型,导致在尝试将BigInteger对象赋值给Long类型的List时出现类型转换异常。

类型转换陷阱,hibernate 原生查询BigInteger 转 Long 出错问题&spm=1001.2101.3001.5002&articleId=91872560&d=1&t=3&u=dbd7f8c6bf744e91bb1ec86d7eb72c25)
1363

被折叠的 条评论
为什么被折叠?



