简体   繁体   中英

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. I am doing in following way but getting number of updated rows instead of generated key which is id in this case.

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 ?

Spring JDBC does not allow to retrieve the generated keys when you invoke executeBatch method. This is because internally it invokes executeBatch() method of java.sql.PreparedStatement , which only returns the count of rows affected. An alternate approach would be to execute the insert statement using executeAndReturnKey method multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM