I have a scenario where my table has an autogenerated id column and I need to bulk insert items into db and fetch the generated ids. Is there any way I can achieve that?
This is my table:
CREATE TABLE test_table (
`id` SERIAL NOT NULL,
`name` VARCHAR(100) NOT NULL,
`created_date` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
To save a list of items into this table, the code I am using:
String initialSql = "INSERT INTO test_table(`name`,`created_date`) VALUES ";
List<String> values =
dummyEntities.stream()
.map(dummyEntity -> "('" + dummyEntity.getName() + "','"
+ dummyEntity.getCreatedDate().atZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime().toString() + "')")
.collect(Collectors.toList());
String sqlToExecute = initialSql + String.join(",", values);
client.execute(sqlToExecute)
.//Then what?
The generated SQL statement (from DEBUG Logs):
2020-09-15 18:59:32.613 DEBUG 44801 --- [actor-tcp-nio-1] o.s.d.r2dbc.core.DefaultDatabaseClient : Executing SQL statement [INSERT INTO test_table(`name`,`created_date`) VALUES ('Abhi57','2020-09-15T13:29:29.951964'),('Abhi92','2020-09-15T13:29:29.952023')]
I even tried using ConnectionFactory
, still no clue
Mono.from(connectionFactory.create())
.map(Connection::createBatch)
.map(batch -> {
dummyEntities.forEach(dummyEntity -> {
String sql = String.format("INSERT INTO `test_table` (`name`,`created_date`) VALUES ('%s','%s');", dummyEntity.getName(),
dummyEntity.getCreatedDate().atZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime().toString());
batch.add(sql);
});
return batch;
})
.flatMap(batch -> Mono.from(batch.execute()))
.//Then what?
For reference, dummyEntities
variable holds a list of DummyEntity
objects. And the DummyEntity
class looks like this:
@Table("test_table")
public class DummyEntity implements Persistable<Long> {
@Id
@Column("id")
private Long id;
@Column("name")
private String name;
@Column("created_date")
private OffsetDateTime createdDate;
//Getter,Setter
@Override
public boolean isNew() {
return id == null;
}
}
Dependencies used: 2.3.2.RELEASE
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
implementation 'dev.miku:r2dbc-mysql:0.8.2.RELEASE'