Search code examples
javaspringspring-jdbc

Spring Jdbc 4 transaction management


I'm new to Spring (even to version 4.0.3 that I am currently using). In some code I have to extend, JdbcTemplate is uniquely used, an instance is shared among objects to keep all the sql statements under the same transaction. I'd like to use NamedParameterJdbcTemplate so I get one by using

NamedParameterJdbcTemplate npJT = new NamedParameterJdbcTemplate(givenJdbcTemplate.getDataSource());

Sadly npJT and givenJdbcTemplate look not to share the same transaction. This is an issue for me, how can I overcome this problem and keep all the sql instruction I'll do by using npJT in the same transaction as givenJdbcTemplate?


Solution

  • Just use the other constructor which can take a JdbcTemplate as a parmeter and pass your JdbcTemplate to it.

    NamedParameterJdbcTemplate npJT = new NamedParameterJdbcTemplate(givenJdbcTemplate);