2

I had read several articles on obtaining Connection using Spring DataSource.

But in our Company Setup, connection object is obtained through already configured environment. Following the sample code:

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

    Connection connection = RequestUtils.getConnection(pool);

Hence, After reading this tutorial

I am confused on using JDBCTemplate using connection object from above code.

4

2 回答 2

3

我相信 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));
于 2012-07-10T09:59:59.663 回答
2

实际上,Spring 已经提供了 SingleConnectionDataSource 实现(在 4.1.7 版本中已经看到)。

它甚至允许您通过模板抑制连接关闭。

于 2016-02-17T13:11:46.867 回答