使用Spring JDBCTemplate在数据库中插入新数据记录后如何获取生成的ID?

Bra*_*Zhu 5 database spring unique persistent jdbctemplate

当我使用Spring JDBCTemplate时,我得到了一个非常常见的问题,我想在将新数据记录插入数据库后获取ID值,此ID值将被引用到另一个相关表中.我尝试了以下方式插入它,但我总是返回1而不是它真正的唯一ID.(我使用MySQL作为数据库)

public int insert(BasicModel entity) {
    String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);

    log.info("SQL Statement for inserting into: " + insertIntoSql);

    return this.jdbcTemplate.update(insertIntoSql);
}
Run Code Online (Sandbox Code Playgroud)

Tri*_*tan 9

您可以使用@Tomasz Nurkiewicz答案,它肯定有效,但您不需要:Spring提供SimpleJdbcInsert,它“提供元数据处理来简化构造基本插入语句所需的代码”。

@Repository
public class UserDao {

    private JdbcTemplate jdbcTemplate;
    private SimpleJdbcInsert insertIntoUser;

    @Autowired
    public UserDao(DataSource datasource) {
        jdbcTemplate = new JdbcTemplate(datasource);
        insertIntoUser = new SimpleJdbcInsert(jdbcTemplate).withTableName("user").usingGeneratedKeyColumns("id_user");
    }

    public Number insertUser(User u) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("name", u.getName());

        return insertIntoUser.executeAndReturnKey(parameters);
    }
}

Run Code Online (Sandbox Code Playgroud)

insertUser返回的“Number”是为用户插入生成的id_user。


Tom*_*icz 6

JdbcTemplate.update() 收益:

受影响的行数

这始终1INSERT声明.不同的数据库支持以不同的方式生成密钥提取,但大多数JDBC驱动程序都抽象出来并JdbcTemplate支持此功 引用12.2.8检索自动生成的密钥

update()便利方法支持由数据库生成主键的检索.这种支持是JDBC 3.0标准的一部分; 有关详细信息,请参阅规范的第13.6章.

基本上你需要这个更冗长的陈述:

final String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(
  new PreparedStatementCreator() {
    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
      return connection.prepareStatement(insertIntoSql, new String[] {"id"});
    }
  }, keyHolder);

return keyHolder.getKey().intValue();
Run Code Online (Sandbox Code Playgroud)


小智 6

@panadol-chong,@tomasz-nurkiewicz 的代码需要进行一些小修改才能在这里工作。

final String SQL = "INSERT INTO ... RETUNING id";

KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(connection -> {
    PreparedStatement ps = connection.prepareStatement(SQL, 
                           Statement.RETURN_GENERATED_KEYS);

    return ps;
}, keyHolder);

return keyHolder.getKey().intValue();
Run Code Online (Sandbox Code Playgroud)

主要区别在于Statement.RETURN_GENERATED_KEYS.