1.update方法选择
使用的jdbcTemplate对象的update方法为下面这个重载形式
int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
PreparedStatementCreator 是一个接口,其实现类的createPreparedStatement(Connection)方法负责创建一个PreparedStatement实例
而KeyHolder是一个接口,其实现类GeneratedKeyHolder可以拿到自动生成的主键值
先实例化一个GeneratedKeyHolder对象,用于等会儿取主键值
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
调用jdbcTemplate对象的update()方法,传入一个PreparedStatementCreator的匿名内部类对象和上一步实例化的对象keyHolder
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user(id, username, email, password, phoneNum) values(?,?,?,?,?)"
,PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);
preparedStatement.setObject(2,user.getUsername());
preparedStatement.setObject(3,user.getEmail());
preparedStatement.setObject(4,user.getPassword());
preparedStatement.setObject(5,user.getPhoneNum());
return preparedStatement;
},keyHolder);
注意:不要忘记指定PreparedStatement.RETURN_GENERATED_KEYS,否则拿不到主键值
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user(id, username, email, password, phoneNum) values(?,?,?,?,?)"
,PreparedStatement.RETURN_GENERATED_KEYS);
3.lambda表达式简化
jdbcTemplate.update(connection -> {
PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user(id, username, email, password, phoneNum) values(?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setObject(1,null);
preparedStatement.setObject(2,user.getUsername());
preparedStatement.setObject(3,user.getEmail());
preparedStatement.setObject(4,user.getPassword());
preparedStatement.setObject(5,user.getPhoneNum());
return preparedStatement;
},keyHolder);
4.通过keyHolder对象取生成的主键值
Long id=keyHolder.getKey().longValue();
使用jdbcTemplate获取插入数据后自增长的主键值,步骤:
1)实例化GeneratedKeyHolder对象keyHolder用于取主键
2)调用jdbcTemlate对象update方法,传入PreparedStatementCreator匿名内部类对象,编写数据库操作;传入keyHolder
3)通过keyHolder取生成的主键