解决java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long异常

下面代码段,用jdbcTemplate.queryForMap查询数据库表的ID时,虽然编译通过没有报错,但会有问题:

try {
            Map<String,Object> userPo = jdbcTemplate.queryForMap("select * from auth_user where username='" + username + "'");
            if (userPo == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            
            Long id = (Long)userPo.get("id");  //这行代码会报类型转换错误
            String password = (String)userPo.get("password");

            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from auth_user_role where user_id=" + id);
            if (!CollectionUtils.isEmpty(list)) {
                for (Map<String,Object> po : list) {
                    String roleCode = (String)po.get("role_code");
                    authorities.add(new SimpleGrantedAuthority(roleCode));
                }
            }
            return new User(username, password, authorities);
        }catch(Exception ex){
            ex.printStackTrace();
        }

用Postman调用API报错如下:

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
...

解决办法:

//用下面这行代码代替原来的代码(Long)userPo.get("id"),直接转换为Long类型
Long id = ((Integer)userPo.get("id")).longValue();

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值