11

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?

2 Answers2

34

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
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Thanks for the work around, but nevertheless I've ended up implementing it in my application context. –  Jun 24 '10 at 10:36
  • 1
    +1 This makes perfect sense deep down in some Hibernate listener code of mine, where I already have the current open connection in my hand. – Stefan Haberl Mar 19 '14 at 08:11
2

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
  • 305,152
  • 44
  • 369
  • 561