【问题标题】:How to implement saveAll using R2DBC-DatabaseClient?如何使用 R2DBC-DatabaseClient 实现 saveAll?
【发布时间】:2020-10-07 17:31:14
【问题描述】:

如何使用DatabaseClient 实现ReactiveCrudRepository 中的saveAll 方法?

这是我的实现 - 遗憾的是它不起作用。

@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()
}

}

【问题讨论】:

    标签: java spring spring-boot kotlin r2dbc


    【解决方案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();
    }
    

    【讨论】:

      【解决方案2】:

      使用Statement.add方法绑定多个参数。

      this post 中查看我的示例。

      【讨论】:

        猜你喜欢
        • 2020-01-02
        • 1970-01-01
        • 2019-11-01
        • 2019-08-18
        • 2021-06-09
        • 2021-12-14
        • 1970-01-01
        • 2021-01-13
        • 2021-06-22
        相关资源
        最近更新 更多