开发者

Instantiating a JdbcTemplate from a java.sql.Connection

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜