How to get generated keys using SimpleJdbcInsert and executeBatch with MYSQL JDBC driver?

I want to insert several records at a time and get the identifier of each record, which is automatically incremented. I do as follows, but I get the number of updated rows instead of the generated key, which in this case is 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 is the Person bean. So, how can I get the automatically generated key, which is id, for added records?

+4
source share
1 answer

Spring JDBC executeBatch. , executeBatch() java.sql.PreparedStatement, . insert executeAndReturnKey .

0

All Articles