当前位置:   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

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

  1. try {
  2. Map<String,Object> userPo = jdbcTemplate.queryForMap("select * from auth_user where username='" + username + "'");
  3. if (userPo == null) {
  4. throw new UsernameNotFoundException("用户名不存在");
  5. }
  6. Long id = (Long)userPo.get("id"); //这行代码会报类型转换错误
  7. String password = (String)userPo.get("password");
  8. //用户权限
  9. List<SimpleGrantedAuthority> authorities = new ArrayList<>();
  10. List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from auth_user_role where user_id=" + id);
  11. if (!CollectionUtils.isEmpty(list)) {
  12. for (Map<String,Object> po : list) {
  13. String roleCode = (String)po.get("role_code");
  14. authorities.add(new SimpleGrantedAuthority(roleCode));
  15. }
  16. }
  17. return new User(username, password, authorities);
  18. }catch(Exception ex){
  19. ex.printStackTrace();
  20. }

用Postman调用API报错如下:

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

解决办法:

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/604690
推荐阅读
相关标签
  

闽ICP备14008679号