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开发者_如何学运维bcTemplate
from 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.
精彩评论