Search code examples
javaspringjdbcjdbctemplatespring-transactions

Spring Transaction (@Transaction) with Plain JDBC without JdbcTemplate


I have plain JDBC code which is doing transaction management using Connection Interface. I wanted to switch to Spring Transaction Management in small steps.

Firstly I want to provide PlatformTransactionManager for my datasource and annotate my class / methods with @Transaction and keep my other logic same ie. using connection / PreparedStatement etc.

All the examples, which I see use JdbcTemplate. I was wondering can Spring Transaction be used without JdbcTemplate?


Solution

  • Technically it is possible to use @Transactional without JdbcTemplate . But if you try to do it , you will sooner or later find that you are re-inventing what the things that are already done by JdbcTemplate.

    What @Transactional does is that before executing a @Transactional method , it will help you to get a JDBC Connection from the DataSource , and start a transaction on this Connection .The JDBC Connection will then stored in a ThreadLocal.

    That means if you do it without JdbcTemplate , you have to manually get this Connection from that ThreadLocal such that you can create a JDBC Statement from it for executing your SQL. Not to mention you have to manually release the JDBC resources such Statement , ResultSet etc. properly by yourself which all of these things are already take care by JdbcTemplate.

    But if you have already implemented these JDBC codes manually and just want to let @Transactional to handle the transaction , you could try to inject the DataSource to your bean and then use the following method to get the Connection for your JDBC codes use :

        Connection connection = DataSourceUtils.getConnection(dataSource);
    

    Also checkout JdbcTemplate#execute(ConnectionCallback<T> action) , it is useful for migrating the existing JDBC codes that expects a JDBC Connection to work on to JdbcTemplate.