JdbcTemplate可以通过几种方式获取数据库生成的主键:
- 使用查询返回主键:
INSERT INTO user (name) VALUES ('John')
SELECT LAST_INSERT_ID()
然后使用queryForObject()查询并返回主键:
String sql1 = "INSERT INTO user (name) VALUES (?)";
String sql2 = "SELECT LAST_INSERT_ID()";
jdbcTemplate.update(sql1, "John");
Integer key = jdbcTemplate.queryForObject(sql2, Integer.class);
- 将主键列定义为IDENTITY или AUTOINCREMENT:
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50)
)
插入记录后,可以通过调用getGeneratedKeys()方法获取生成的主键:
String sql = "INSERT INTO user (name) VALUES (?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(sql, "John", keyHolder);
Number key = keyHolder.getKey();
- 定义返回主键的PreparedStatementCreator:
PreparedStatementCreator psc = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
return ps;
}
};
jdbcTemplate.update(psc, "John");
ResultSet rs = ps.getGeneratedKeys();
rs.next();
Integer key = rs.getInt(1);
PreparedStatementCreator可以在构造PreparedStatement时定义返回主键。
所以,JdbcTemplate通过以上3种方式,可以方便地获取数据库生成的主键:
- 执行查询语句获取
- 定义主键列为自动增长,使用GeneratedKeyHolder获取
- 定义PreparedStatementCreator并返回主键ResultSet