![](/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.