Spring's JdbcTemplate and Transactions

loyalflow picture loyalflow · Sep 28, 2012 · Viewed 54k times · Source

When using JdbcTemplate, do I need to explicitly configure transactions?

My code layout looks like the following:

I will have a UserDao that will be injected into my UserService, and then my Controllers will make calls on methods in my UserService.

I want to keep things as simple as possible transaction wise, and I don't need multiple database calls to span a transaction.

By default, do I have to do anything in my configuration file or use a @Transaction annotation anywhere?

Now say in my controller I need to make 2 calls on my userService and accountService, could I explicitly wrap it in a transaction somehow?

userService.updateUser(user);
accountService.updateXXX(...);

Answer

David Grant picture David Grant · Sep 28, 2012

Yes, JdbcTemplate is not a substitute for transaction management. You still benefit from database transactions, so userService.updateUser will operate in a database transaction, but if accountService.updateXXX fails, userService.updateUser will not rollback.

If you don't want to use AOP, you can use TransactionTemplate instead. See programmatic transaction management in the Spring Reference Documentation.

One pattern I've seen before is for the MVC controller class to invoke a business service, which encapsulates the operation. The method of the business class could then be annotated @Transactional.