views:

33

answers:

2

Hi!

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 JdbcTemplatefrom an existing java.sql.Connection?

+1  A: 

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.

duffymo
+3  A: 

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.

Bozho
Thanks for the work around, but nevertheless I've ended up implementing it in my application context.
Bernhard V