获取新添加到数据库的数据的自增长id
作者:互联网
/** * 添加用户信息到sys_user表 * @param user * @return */ @Override public Long save(User user) { //创建PreparedStatementCreator PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { //使用原始jdbc完成PreparedStatement的组建 PreparedStatement preparedStatement = con.prepareStatement( "insert into sys_user values (?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS //返回数据库自动生成的userId,封装在keyHolder中 ); preparedStatement.setObject(1,user.getId()); preparedStatement.setString(2,user.getUsername()); preparedStatement.setString(3,user.getEmail()); preparedStatement.setString(4,user.getPassword()); preparedStatement.setString(5,user.getPhoneNum()); return preparedStatement; } }; //创建keyHolder GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(preparedStatementCreator,keyHolder); //获取自动生成的userId long userId = keyHolder.getKey().longValue(); /*jdbcTemplate.update("insert into sys_user values (?,?,?,?,?)", user.getId(),//用户id自动生成,这里的值为null user.getUsername(), user.getEmail(), user.getPassword(), user.getPhoneNum());*/ //返回当前保存用户的id,id是数据库自动生成的 return userId; }
标签:keyHolder,preparedStatement,数据库,userId,添加,user,id,setString 来源: https://www.cnblogs.com/shpen/p/15851282.html