4

I'm designing a pretty standard Spring MVC application, and I'm trying to figure out where the responsibility for transaction management should lie.

I've been reading Java Transaction Design Strategies, and the one that I think best suits is the Server Delegate one, where the controller is what manages the transactions, and the services and DAOs are oblivious to the transactions.

Somehow, this doesn't feel right. My gut feeling is that the services are the ones that should control the transactions, but I have cases where a controller may call several services to perform an action.

How have you handled Transactions in MVC applications before, and where do you consider the best place for handling the transactions is?

1
  • 1
    You want to move the transactions as high in the chain as possible. The entity managing the transactions should be aware of the process as a whole. Hence the controller is usually a good fit.
    – Andrea
    Commented May 29, 2012 at 14:41

3 Answers 3

5

I find it useful to implement a Service Facade that decouples the implementation of services from the service contract. The Controller from the presentation tier (your MVC stuff) should be able to make a single call to a Service Facade, which then orchestrates the calls to one or more "service" objects/methods, and returns whatever the service contract says it needs to return.

In this architecture, the Service Facade would also be the place to hook in your transaction management.

3

It's my understanding that the controller should mainly be responsible for communicating with the business layer and preparing the view data when necessary. In that case, it shouldn't have any knowledge about transactions; they should be kept at a lower layer.

When the controller needs to execute some logic that consists of multiple steps where a single transaction would be desired, that logic should be rolled up into a method in the business layer. When managing transactions with Spring, you can easily define a service method as transactional, and how nested calls should handle their transactions: whether to pick up the existing transaction if available, always create new, etc.

1

The service layer is most naturally suited place for transaction demarcation in MVC apps no matter which service layer pattern you use.

However, sometimes concessions should be made for a specific application when it makes sense, so I would not be overly dogmatic about it. Just make sure that you use declarative transaction management so you can move transactions around to the most appropriate place without affecting your application code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.