batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames) .map(mapper) .iterator(); } else { batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames) .mapTo(magic.elementType(batch.getContext())) .iterator();
@Test public void testBatchInsertWithKeyGenerationAndExplicitSeveralColumnNames() { PreparedBatch batch = h.prepareBatch("insert into something (name) values (?) "); batch.add("Brian"); batch.add("Thom"); List<IdCreateTime> ids = batch.executeAndReturnGeneratedKeys("id", "create_time") .map((r, ctx) -> new IdCreateTime(r.getInt("id"), r.getDate("create_time"))) .list(); assertThat(ids).hasSize(2); assertThat(ids).extracting(ic -> ic.id).containsExactly(1, 2); assertThat(ids).extracting(ic -> ic.createTime).doesNotContainNull(); }
@Test public void testBatchInsertWithKeyGenerationAndExplicitColumnNames() { PreparedBatch batch = h.prepareBatch("insert into something (name) values (?) "); batch.add("Brian"); batch.add("Thom"); List<Integer> ids = batch.executeAndReturnGeneratedKeys("id").mapTo(Integer.class).list(); assertThat(ids).containsExactly(1, 2); List<Something> somethings = h.createQuery("select id, name from something") .mapToBean(Something.class) .list(); assertThat(somethings).containsExactly(new Something(1, "Brian"), new Something(2, "Thom")); }
@Test public void testBatchInsertWithKeyGeneration() { Jdbi db = Jdbi.create("jdbc:hsqldb:mem:jdbi-batch-keys-test", "sa", ""); try (Handle h = db.open()) { h.execute("create table something (id integer not null generated by default as identity (start with 10000), name varchar(50))"); PreparedBatch batch = h.prepareBatch("insert into something (name) values (?)"); batch.add("Brian"); batch.add("Thom"); List<Integer> ids = batch.executeAndReturnGeneratedKeys().mapTo(int.class).list(); assertThat(ids).containsExactly(10000, 10001); List<Something> somethings = h.createQuery("select id, name from something") .mapToBean(Something.class) .list(); assertThat(somethings).containsExactly(new Something(10000, "Brian"), new Something(10001, "Thom")); } } }