![](/img/trans.png)
[英]How to get generated keys by executeBatch without ArrayIndexOutOfBoundsException?
[英]How to get generated keys using SimpleJdbcInsert and executeBatch with MYSQL JDBC driver?
我想一次插入多个记录并获取每个记录的自动增量的id。 我正在按照以下方式进行,但获取更新行的数量而不是生成的密钥,在这种情况下为id。
public int[] addPersons(List<Person> persons)
{
SqlParameterSource[] records= new BeanPropertySqlParameterSource[persons.size()] ;
int i = 0;
for (Person person: persons)
{
records[i]= new BeanPropertySqlParameterSource(person);
i++;
}
SimpleJdbcInsert insertPerson=new SimpleJdbcInsert(dsource).withTableName("PersonTable").usingGeneratedKeyColumns("id");
int [] ids= insertPerson.executeBatch(records);
return ids;
}
这里的人是豆。 那么如何为添加的记录获取自动生成的密钥id?
当您调用executeBatch
方法时,Spring JDBC不允许检索生成的键。 这是因为它在内部调用java.sql.PreparedStatement
executeBatch()
方法,该方法仅返回受影响的行数。 另一种方法是多次使用executeAndReturnKey
方法执行insert
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.