无法在查询中设置List<...>参数

问题描述 投票:0回答:1

我无法添加 List<...> 参数,或者更确切地说是 ArrayList ($2)。

如果我只是放入 List<...> listId,则会收到错误:无法编码 java.util.ArrayList 类型的参数 ([192, 193, 194, ....

如果我设置了listId.toArray(),那么就没有错误,但是查询没有执行,甚至没有任何内容写入日志中。

请求很简单,没有错误: “更新“架构”。“表”SET“列”= $1,其中“id”在($2)中”

这个问题与 postgres 和 mssql 都相关,我的驱动程序和运行时的查询表单正在改变。

请帮我解决问题...

    public <S, T> Mono<Boolean> update(ConnectionFactory connectionFactory, String query, S param, List<T> listId) {
        return Mono.usingWhen(connectionFactory.create(),
                        connection -> {
                            Statement statement = connection.createStatement(query);
                            statement.bind("$1", param);
                            statement.bind("$2", listId);

                            return Mono.from(statement.execute());
                        },
                        Connection::close)
                .map(el -> true)
                .doOnSuccess((a) -> log.info("Update Success!"))
                .onErrorResume(e -> {
                    log.error("ERROR update : \n{}", e.getMessage());
                    return Mono.just(false);
                });
    }
java r2dbc r2dbc-postgresql r2dbc-mssql
1个回答
0
投票

您正在使用基于原始位置的参数绑定,您应该在代码中添加这样的参数。

statement.bind(0, param);
statement.bind(1, listId);

请注意,在您的 SQL 中,您应该使用

$1
,并使用
$2
作为参数位置。但使用
statement.bind
时,它以 0 开头。

Spring R2dbc 提供了一个包装客户端 -

DatabaseClient
,可以轻松地使用命名参数执行 SQL。

public Mono<Long> deleteAllById(List<UUID> ids) {
    return this.databaseClient.sql("DELETE FROM posts WHERE id in (:ids)")
        .bind("ids", ids)
        .fetch()
        .rowsUpdated();
}

以上所有示例均基于 Postgres。

在此处使用

ConnectionFactory
检查我的示例:https://github.com/hantsy/spring-r2dbc-sample/blob/master/connection-factories/src/test/java/com/example/demo/PgTests.java

使用

DatabaseClient
的示例:https://github.com/hantsy/spring-r2dbc-sample/tree/master/database-client

© www.soinside.com 2019 - 2024. All rights reserved.