Kumar
Kumar

Reputation: 1666

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?

Upvotes: 2

Views: 5488

Answers (2)

Ken Chan
Ken Chan

Reputation: 90417

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.

Upvotes: 3

mohammedkhan
mohammedkhan

Reputation: 975

Yes it's possible. Adding a @Transactional annotation to your methods, as long as they follow the correct procedure should make your methods transactional. But as others have mentioned if you're in the process of updating your app you might as well ditch plain JDBC and move across to Spring JPA/JDBC (depending on which version of Spring you're using).

Upvotes: 2

Related Questions