-
Hello everyone! I am trying to write a method that will do a batch insert of objects, and then get back all the primary keys from the insert and put them in the respective beans. Is this possible? I noticed that the PreparedBatch object has an "executeAndReturnGeneratedKeys()" method, but I cannot figure out how to use it. Here's a simplified example of what I'm trying to do:
My table (and my Order class) has an "id" column which is the auto-generated primary key. The batch insert does work, but the 'id' attribute in the beans is never populated. To be fair, I could be going about this completely wrong/inefficiently, so please feel free to correct me. Any help you can provide will be greatly appreciated! Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
So this works fine with Postgres: @Test
void testBatchInsertReturningIds() {
List<String> names = Arrays.asList(
"Brian",
"Steven",
"Matthew",
"Artem",
"Marnick",
"Henning");
PreparedBatch batch = handle.prepareBatch("insert into something (name) values (?) returning id");
names.forEach(batch::add);
BatchResultBearing batchResult = batch.executePreparedBatch("id");
List<Integer> ids = batchResult.mapTo(Integer.class).list();
assertThat(ids).hasSize(6);
assertThat(ids).containsExactly(1, 2, 3, 4, 5, 6);
} The challenge is that returning data from the database is highly dependent on the database itself. E.g. for Postgres you need the |
Beta Was this translation helpful? Give feedback.
-
do "INSERT INTO ... RETURNING *" and BatchResultBearing batchResult = batch.executePreparedBatch("*");
List<Order> ids = batchResult.mapTo(Order.class).list(); This assumes you have a mapper for the |
Beta Was this translation helpful? Give feedback.
So this works fine with Postgres:
The challenge is that returning data from the d…