用GeneratedKeyHolder获得新建数据主键值

 public User createUser(final User user) {

        final String sql = "insert into sys_users(username, password, salt, locked) values(?,?,?, ?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(new PreparedStatementCreator() {

            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});

                psst.setString(1, user.getUsername());

                psst.setString(2, user.getPassword());

                psst.setString(3, user.getSalt());

                psst.setBoolean(4, user.getLocked());

                return psst;

            }

        }, keyHolder);

        user.setId(keyHolder.getKey().longValue());

        return user;

    }

 

你可能感兴趣的:(key)