views:

1200

answers:

2

The project I'm working on uses straight JDBC data access in all its boilerplate glory and doesn't use any transactions. I feel like using transactions and simplifying the way data access methods are written is important, especially with some changes being made currently. The project has been around for quite a while and isn't suited to an ORM framework. It also uses lots of Singletons (ugh) and untangling it to make it able to use dependency injection would be a fair amount of work and I don't think I could convince anyone that we should do that now.

I like the interface of Spring JDBC, specifically through its SimpleJdbcTemplate. My question is about how to enable some simple (per servlet request) transactions for this, without having to set anything programmatically in every data access method or using the Spring IoC container or AOP. I've played around with my own architecture that ends up with an interface similar to SimpleJdbcTemplate's and can use a single request-local connection and transaction when calls to it are made in the context of a request (through a ServletRequestListener with a ThreadLocal). It seems to work well, but I think using a good external library like Spring JDBC would be preferable.

Anyone have any experience with this?

+5  A: 

Perhaps you could use TransactionTemplate and TransactionCallback as described in Programmatic Transaction Management?

toolkit
This doesn't work quite how I was thinking, as it would require programmatically wrapping calls using the TransactionTemplate at a higher application level rather than just having every call to the JdbcTemplate use a request-local transaction if possible. It should work fine though.
ColinD
A: 

Spring handles transactions for you declaratively without you having to worry about writing AOP classes. If you're using JDK 5 or higher and Spring 2.5, you have it even better with annotations.

I would disagree with per-servlet transactions. You should have a service tier, which is the part of the app that knows about units of work. Controllers call into services, which handle transactions.

duffymo
I mentioned in the question that the application is not currently in the Spring container and couldn't easily be moved to it. I'd love to use the declarative transactions like that if I could.
ColinD