简体   繁体   English

没有数据源的Spring JDBC连接

[英]Spring JDBC connection without dataSource

I had read several articles on obtaining Connection using Spring DataSource. 我已经阅读了几篇有关使用Spring DataSource获得Connection的文章。

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. 我对通过上述代码中的连接对象使用JDBCTemplate感到困惑。

I believe JdbcTemplate is not designed to work against a Connection as what you expected. 我相信JdbcTemplate并非旨在按您期望的那样对Connection起作用。 As a workaround, if you are fine to create a separate JdbcTemplate for each connection you created, you may wrap your connection in a thin wrapper of DataSource, and feed it to JdbcTemplate. 作为一种解决方法,如果可以为创建的每个连接创建单独的JdbcTemplate,则可以将连接包装在DataSource的薄包装中,并将其提供给JdbcTemplate。

I think it should work but I haven't tried it anyway... 我认为应该可以,但是我还是没有尝试过...

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));

Actually, Spring already provided SingleConnectionDataSource implementation (have seen in version 4.1.7). 实际上,Spring已经提供了SingleConnectionDataSource实现(在版本4.1.7中已经看到)。

It is even allows you to supress connection closing by template. 它甚至允许您禁止通过模板关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM