在不使用其他框架的情况下,使用JdbcTemplate对象的 update(PreparedStatementCreator psc,KeyHolder generatedKeyHolder) 方法实现获取数据库刚插入数据的自增ID值。
Dao层代码如下:
public Long save(final User user) {
PreparedStatementCreator creator = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("insert into user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);
preparedStatement.setString(2,user.getUsername());
preparedStatement.setString(3,user.getEmail());
preparedStatement.setString(4,user.getPassword());
preparedStatement.setString(5,user.getPhoneNum());
return preparedStatement;
}
};
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
//keyHolder接收返回的自增id
jdbcTemplate.update(creator,keyHolder);
long userId = keyHolder.getKey().longValue();
return userId;
}
本文地址:https://blog.csdn.net/m0_48268301/article/details/112686856