PDA

View Full Version : ServiceFactory, Struts2, Spring, JPA & Transactional?



ajmas
Feb 27th, 2009, 06:44 PM
I am currently using a mix of Struts2, JPA and Spring ORM. This has been working fine, with passing the bean class representing the service via the Struts Action constructor. Transaction works fine here. This also works for transactions:



public <T extends BasicService> T getService(Class<T> clazz) {
WebApplicationContext webAppContext = WebApplicationContextUtils.getWebApplicationContex t(ServletActionContext.getServletContext());
Object obj = webAppContext.getBean(clazz.getSimpleName());
assert( clazz.isInstance(obj));
return (T) obj;
}


Now the architect of the project would like to see we could have our own service factory and use generics. Basically the Struts Action or the servlet would call:


public <T extends BasicService> T getService(Class<T> clazz) {

WebApplicationContext webAppContext = WebApplicationContextUtils.getWebApplicationContex t(ServletActionContext.getServletContext());
ServiceFactory serviceFactory = (ServiceFactory) webAppContext.getBean("ServiceFactory");

return serviceFactory.getService(clazz);
}

This would fetch the service factory and then ask the service factory to instantiate the service. The service factory has a setEntityManager() method with the '@PersistenceContext' annotation. The entity manager is then passed on to the service class being instantiated.

This approach is working fine for reading data from the database, but fails when we try writing the data with:


javax.persistence.TransactionRequiredException: no transaction is in progress

Clearly there is something I am not understanding with the transaction life-span and how it should be initiated. Given this approach how would I initiate the transaction on instance retrieved through the service factory?