gpt4 book ai didi

没有数据源的Spring JDBC连接

转载 作者:行者123 更新时间:2023-12-02 22:36:57 25 4
gpt4 key购买 nike

我看过几篇关于使用 Spring DataSource 获取 Connection 的文章。

但在我们的公司设置中,连接对象是通过已配置的环境获得的。按照示例代码:

 String pool = PropertyFileReader.getPropertyValue("database.properties", "development.connectionPool");

Connection connection = RequestUtils.getConnection(pool);

因此,阅读此文后tutorial

我对使用上述代码中的连接对象使用 JDBCTemplate 感到困惑。

最佳答案

我相信 JdbcTemplate 的设计并不是像您期望的那样针对 Connection 工作。作为解决方法,如果您可以为您创建的每个连接创建一个单独的 JdbcTemplate,您可以将您的连接包装在 DataSource 的薄包装器中,并将其提供给 JdbcTemplate。

我认为它应该可以,但我还没有尝试过......

class SingleConnectionDataSource implements DataSource {
private Connection connection;
public SingleConnectionDataSource(Connection connection) {
this.connection = connection;
}

public Connection getConnection() {
return this.connection;
}
public Connection getConnection(String username, String password) {
return this.connection;
}
}

// at the place you want to use JdbcTemplate
Connection conn = blablabla; // your own way to get it
JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn));

关于没有数据源的Spring JDBC连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com