Discuss / Java / 2处疑惑在这篇文章中的

2处疑惑在这篇文章中的

Topic source

对这句话 "JDBC操作都可以使用保底的execute(ConnectionCallback)方法" 有疑惑,

因为我发现 jdbcTemplate.update 也可以传入一个 Connection,这样的话 JdbcTemplate.execute 方法好像显得重复没必要了

public User register(String email, String password, String name) {
    // ...
    if (1 != jdbcTemplate.update(
        // 这个参数 conn 是一个 Connection 对象
        (conn) -> {
            // ...
        },
        holder)
    ) {
        throw new RuntimeException("Insert failed.");
    }
    // ...
}

另一个问题是:为什么 update 传入参数 Connection conn可以缩写成 conn,但是在 jdbcTemplate.execute 必须写完整,否则会报错 “Ambiguous method call” 

jdbcTemplate.update((conn) -> { // ... }...
public User getUserById(long id) {
    // 如果把 Connection conn 给替换成 conn 将会报错
    return jdbcTemplate.execute((Connection conn) -> {
        // ...
    });
}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

Ambiguous method call是你的局部变量有重名的conn

杆子BDZ

#3 Created at ... [Delete] [Delete and Lock User]

第二个问题如果是报错The method execute(ConnectionCallback<T>) is ambiguous for the type JdbcTemplate 的话,应该是因为JdbcTemplatez 这个类里面有多个 execute() 方法。如果不指明Lambda表达式的参数的类型的话,对于 JdbcTemplate 来说就是摸棱两可的(ambiguous)。


  • 1

Reply