Spring3.0.5 获取表中自增的主键(mysql)

时间:2022-06-05 15:27:54
    public int addWsstxCotent(final WsstxContent wsstxContent) {
final String sql = "insert into wsstx_content(sstx_type,sstx_content,sstx_title,opr_time,ts_tag) values(?,?,?,now(),?)";
// this.jdbcTemplate.update(sql,
// new Object[]{wsstxContent.getSstxType(), wsstxContent.getSstxContent(),wsstxContent.getSstxTitle(), wsstxContent.getTsTag()});
KeyHolder keyHolder = new GeneratedKeyHolder();
this.jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, wsstxContent.getSstxType());
ps.setString(2, wsstxContent.getSstxContent());
ps.setString(3, wsstxContent.getSstxTitle());
ps.setString(4, wsstxContent.getTsTag());
return ps;
}
} , keyHolder);
int generatedId = keyHolder.getKey().intValue();
return generatedId;
}