[英]How to get generated keys using SimpleJdbcInsert and executeBatch with MYSQL JDBC driver?
I want to insert multiple records at a time and get the id of each record which is auto-increment. 我想一次插入多个记录并获取每个记录的自动增量的id。 I am doing in following way but getting number of updated rows instead of generated key which is id in this case.
我正在按照以下方式进行,但获取更新行的数量而不是生成的密钥,在这种情况下为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;
}
Here Person is the bean. 这里的人是豆。 So how can I get the auto generated key which is id, for the records added ?
那么如何为添加的记录获取自动生成的密钥id?
Spring JDBC does not allow to retrieve the generated keys when you invoke executeBatch
method. 当您调用
executeBatch
方法时,Spring JDBC不允许检索生成的键。 This is because internally it invokes executeBatch()
method of java.sql.PreparedStatement
, which only returns the count of rows affected. 这是因为它在内部调用
java.sql.PreparedStatement
executeBatch()
方法,该方法仅返回受影响的行数。 An alternate approach would be to execute the insert
statement using executeAndReturnKey
method multiple times. 另一种方法是多次使用
executeAndReturnKey
方法执行insert
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.