jdbcTemplate插入数据库返回自增主键

@Override
public Integer saveHgzdy(final TabNcpHgzdy b) {
Object[] params = new Object[]{
b.getLx(),
b.getQyId(),
b.getKjzt(),
b.getScjyztId()
};
// 必须要有keyHolder
KeyHolder keyHolder = new GeneratedKeyHolder();
// 改写如下
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS);
int i = 1;
// 自增主键为null
ps.setObject(i, null);
for (Object p : params){
i++;
// 用Object可以添加null参数
ps.setObject(i, p);
}
return ps;
}
}, keyHolder);
// 返回主键id
return keyHolder.getKey().intValue();
}