当前位置:   article > 正文

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

class java.lang.integer cannot be cast to class java.lang.long (java.lang.in

下面代码段,用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();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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')
...
  • 1
  • 2

解决办法:

//用下面这行代码代替原来的代码(Long)userPo.get("id"),直接转换为Long类型
Long id = ((Integer)userPo.get("id")).longValue();
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/604680
推荐阅读
相关标签
  

闽ICP备14008679号