首页 > 解决方案 > PreparedStatement 未执行且 RowMapper 未调用

问题描述

对于简单的登录访问检查,我将 jdbcTemplate 与以下 DAO 方法一起使用:-

    @Autowired
        JdbcTemplate jdbcTemplate;

        public List<User> hasAccess (String user, String pass) {
            return jdbcTemplate.query(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement("SELECT * FROM SHB_USERS WHERE USER=? AND PASS=?");
                    ps.setString(1, user);
                    ps.setString(2, pass);
                    return ps;
                }
            }, new RowMapper<User>() {
                @Override
                public User mapRow(ResultSet resultSet, int rownum) throws SQLException {
                    String user = resultSet.getString("USER");
                    String pass = resultSet.getString("PASS");
                    User userObj = new User(user, pass);
                    System.out.println(userObj.toString());
                    return userObj;
                }
            });
        }

但不知何故mapRow不叫。PreparedStatement例如,当我使用直接字符串而不是它时,select * from shb_users where rownum <2它可以工作。我是 Spring Boot 新手,无法找出错误。

标签: spring-bootjdbctemplate

解决方案


尽管您已经在代码中发现了问题,但我仍会继续向最终访问此页面的其他用户提及它,同时找到来自mapRow(...).

@Nullable
T mapRow(ResultSet rs,
                   int rowNum)
            throws SQLException

根据 Spring 的官方文档

This method should not call next() on the ResultSet; it is only supposed to map values of the current row.

这解释了在此方法的任何给定执行中,cursor参数内的参数ResultSet rs位于由参数表示的单行rowNum。如果在resultsetpass 处没有行rowNum,则不会执行此方法。


推荐阅读