Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于JdbcTemplate的queryForObject连续查询同一内容会导致nullPointerException #10

Open
Viking18 opened this issue Dec 25, 2017 · 0 comments

Comments

@Viking18
Copy link
Collaborator

代码如下

 public User getUserByName(String username) {
        DataSourceRouterManager.setCurrentDataSourceKey("primary");
        try {
            return (User) jdbcTemplate.queryForObject(
                    "select id,username,password,salt from user_table where username=? ",
                    new Object[]{username}, new RowMapper() {
                        @Override
                        public Object mapRow(ResultSet rs, int rowNum)
                                throws SQLException {
                            User user = new User();
                            user.setUsername((rs.getString("username")));
                            user.setPassword(rs.getString("password"));
                            user.setSalt(rs.getString("salt"));
                            user.setId(rs.getInt("id"));
                            return user;
                        }
                    }
            );
        }
// 如果表中无对应记录,queryForObject会抛出异常,捕获后返回空对象
        catch (EmptyResultDataAccessException e){
            return null;
        }
    }

test方法如下

public String test() {
        String res = "";
        String name = "viking";
        User user= userDao.getUserByName(name);
        User user1 = userDao.getUserByName(name);
        res += user.toString()+user1.toString();
        return res  ;
    }

结果在user.setUsername((rs.getString("username")));行抛出空指针异常

另外如果使用queryForMap则不会这样

public User getUserByName(String username) {
        DataSourceRouterManager.setCurrentDataSourceKey("primary");
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(
                    "select id,username,password,salt from user_table where username=? ",
                    new Object[]{username});
            User user = new User();
            user.setUsername(map.get("username").toString());
            user.setPassword(map.get("password").toString());
            user.setSalt(map.get("salt").toString());
            user.setId(Integer.parseInt(map.get("id").toString()));
            return user;
        }
        catch (EmptyResultDataAccessException e){
            return null;
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant