Christoph Ehscheidt

code and fly

Thoughts, stories and ideas.


Spring 3, REST and transactions

Today I had difficulties to get transactions with a REST service ie. spring mvc working.

The problem was that no persitence call on the entitymanager resulted in a phyical saved entity in the database.
My DAO classes were marked with @Repository and @Transactional Annotations. I was confused because the same DAO class was used in an other project with JSF bindings – without any problems.

The only different of the REST project and the JSF project are the dispatchers that are defined in the web.xml.

The JSF project defined the javax.faces.webapp.FacesServlet

<servlet>  
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>  

In the REST project with the described problem there is defined:

<servlet>  
  <servlet-name>rest</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>  

The difference here is that the DispatcherServlet is looking for a [servlet-name]-servlet.xml configuration file. So I defined my REST related suff there.
Also I defined the following in the web.xml

<listener>  
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>  
<context-param>  
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/rest-context.xml</param-value>
</context-param>  

In the rest-context.xml I put all my entity and datasource related suff.

The interesting point is, that by using this two different configuration files, spring does’t recognise the transaction context. I’m not sure if there is a second context or if it’s just one not working.

The solution to this confusion is to put all configuration from the [servlet-name]-servlet.xml into the servlet-context.xml file.

That’s it!

If anyone can point me out why those two configuration files are not interpreted and working together, you’re welcome to comment! :-)

Cheers

comments powered by Disqus