How to implement saveAll using R2DBC-DatabaseClient?

1.2k views Asked by At

How can I implement a saveAll method like in ReactiveCrudRepository using DatabaseClient?

That's my implementation - Sadly it doesn't work.

@Repository
class AppStartRepo(val client: DatabaseClient) {

suspend fun saveAll(starts: List<AppStart>) {
    val builder = StringBuilder()
    builder.append("INSERT INTO app_start (device_id, platform, last_update) VALUES ")
    for (index in starts.indices) {
        builder.append("(?")
        builder.append(index * 3)
        builder.append(",?")
        builder.append(index * 3 + 1)
        builder.append(",?")
        builder.append(index * 3 + 2)
        builder.append(")")
    }

    var querySpec = client.sql(builder.toString())
    for (index in starts.indices) {
        val start = starts[index]
        querySpec = querySpec.bind(index * 3, start.deviceId)
                .bind(index * 3 + 1, start.platform.toString())
                .bind(index * 3 + 2, start.lastUpdate)
    }

    querySpec.await()
}

}
2

There are 2 answers

0
Hantsy On

Use Statement.add method to bind multiple parameters.

See my example in this post.

0
Rony Nguyen On
@Autowired
private DatabaseClient databaseClient;

public Mono<Integer> saveAll(List<Book> books) {
    var query = new StringBuilder("INSERT INTO book(title, author) VALUES ");
    var bookIterator = books.iterator();
    while(bookIterator.hasNext()) {
        var book = bookIterator.next();
        query.append(String.format("('%s', '%s')", book.getTitle(), book.getAuthor()));
        if(bookIterator.hasNext()) {
            query.append(", ");
        }
    }
    return databaseClient.execute(query.toString()).fetch().rowsUpdated();
}