List(泛型)类型转换陷阱,hibernate 原生查询BigInteger 转 Long 出错问题

本文探讨了在使用Hibernate框架执行原生SQL查询时,返回的数据类型与预期不符的问题。具体表现为查询结果为BigInteger类型而非期望的Long类型,导致在尝试将BigInteger对象赋值给Long类型的List时出现类型转换异常。

在使用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
 

 

转载于:https://my.oschina.net/yukong/blog/842547

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值