英文:
How to implement saveAll using R2DBC-DatabaseClient?
问题
@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()
}
}
英文:
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()
}
}
答案1
得分: 1
@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();
}
英文:
@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();
}
答案2
得分: 0
使用Statement.add
方法绑定多个参数。
在此帖子中查看我的示例。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论