【问题标题】:Spring JDBC connection without dataSource没有数据源的 Spring JDBC 连接
【发布时间】:2012-07-04 09:49:40
【问题描述】:

我已经阅读了几篇关于使用 Spring DataSource 获取连接的文章。

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

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

    Connection connection = RequestUtils.getConnection(pool);

因此,阅读此tutorial

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

【问题讨论】:

  • 我无法正确解释问题或问题吗?

标签: spring jdbctemplate spring-jdbc


【解决方案1】:

我相信 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));

【讨论】:

    【解决方案2】:

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

    它甚至允许你通过模板禁止连接关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多