0

I am working on Spring Batch and Spring Jdbc where I'm using NamedParameterJdbcTemplate's batchUpdate to insert the record into DB and once the records are inserted I want to get the Primary Keys of all inserted records..

Is there any way to get the generated Primary Keys?

List<Person> persons = Arrays.asList(
        Person.create("Dana", "Whitley", "464 Gorsuch Drive"),
        Person.create("Robin", "Cash", "64 Zella Park")
);

String sql = "insert into Person (first_Name, Last_Name, Address) " +
        "values (:firstName, :lastName, :address)";

List<Map<String, Object>> batchValues = new ArrayList<>(persons.size());
for (Person person : persons) {
    batchValues.add(
            new MapSqlParameterSource("firstName", person.getFirstName())
                    .addValue("lastName", person.getLastName())
                    .addValue("address", person.getAddress())
                    .getValues());
}

int[] updateCounts = namedParamJdbcTemplate.batchUpdate(sql,
                           batchValues.toArray(new Map[persons.size()]));
PAA
  • 1
  • 46
  • 174
  • 282

1 Answers1

0

I answered a similar question here

The trick is to use NamedParamJdbcTemplate#query over NamedParamJdbcTemplate#batchUpdate and add returning <generated_column> to your insert sql