开发者

Instantiating a JdbcTemplate from a java.sql.Connection

开发者 https://www.devze.com 2023-01-04 09:30 出处:网络
I want to obtain a JdbcTemplate in my Java code. I\'ve already got a working java.sql.Connection. To create a new JdbcTemplate it would normally need an instance of the javax.sql.DataSource interface.

I want to obtain a JdbcTemplate in my Java code. I've already got a working java.sql.Connection. To create a new JdbcTemplate it would normally need an instance of the javax.sql.DataSource interface.

Is it somehow possible to obtain a new Jd开发者_如何学运维bcTemplatefrom an existing java.sql.Connection?


Technically, you can, using SingleConnectionDataSource

new JdbcTemplate(new SingleConnectionDataSource(connection, false))

However, this is not quite advisable, unless for unit-tests for example.

You'd better use a full-featured DataSource and wire things using spring.


No, JdcbTemplate is a Spring class; Connection is part of the JDK. Connection knows nothing about JdbcTemplate.

The way to do it is to add a JdbcTemplate bean in your Spring app context; then inject it into the classes that need it declaratively.

0

精彩评论

暂无评论...
验证码 换一张
取 消