Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using and controlling Spring transactions within Struts 2 actions

I have been working for a while on a project with the following components:

  • Struts2.1.8.1,
  • Spring 3.0.3
  • JPA 2.0,
  • Hibernate 3

I am using Spring's EntityManager magic... But I'm having problems dealing with transactions inside my actions. For instance, I am setting values on my persisted object in several methods within my class, and I want to be able to rollback if the validate method finds a validation error, or commit these changes otherwise. I have already spent quite a long time reading half of the internet for a comprehensive explanation. Unfortunately, no complete examples exist (at least similar to my stack).

I have stumbled with this thread on a mailing list: @Transactional Spring Annotation in a Struts2 Action does not work. The message I'm linking at seems to have a pretty simple and straightforward solution, using a TransactionInterceptor will do the trick it seems... The problem is that I'm not finding useful information regarding this interceptor.

Anyone here has experience with this technology and can spare a tip and a link or two on how to use Spring transactions inside Struts2 actions?

Thanks!

- Edit 1 -

I have set up a test project if you are interested, just download the file and try it out (or inspect it). Thanks!

like image 467
Federico Cáceres Avatar asked Dec 20 '10 21:12

Federico Cáceres


1 Answers

Generally, controllers/actions/backing beans/etc don't handle transactions. Actions are the web-part of your back-end code - they should only be concerned with gathering request data, and sending response data. The logic itself (including database access) should be done in another layer. E.g. a service layer. So you create another bean, inject it in the action, and make it do the work - userService.register(user). Then configuring transactions on a service layer should be trivial since it is both in the spring documentation and in countless examples:

<tx:annotation-driven /> and @Transactional (btw, make sure you have the <tx:..> now, it might be causing the issue. Even if it works, this does not invalidate my suggestion about the service layer)

like image 57
Bozho Avatar answered Sep 29 '22 21:09

Bozho