title: JPA + Spring: UnexpectedRollbackException when Transaction is REQUIRED, REQUIRES_NEW or NESTED
body: <p>I'm doing my first project with Spring, JPA, and GlassFish 3.1 and I'm having some troubles. I've been looking for a solution for a week, but I have found nothing.</p>
  
  <p>I have an Entity (called Role), a GeneralReposiroty with general methods to access any entity, a RoleRepository which implements particular methods about Role, and a Service class, which calls RoleRepository. Methods of Service class are transactional, but I get RollBackException if the propagation property is REQUIRED, REQUIRES_NEW or NESTED. If propagation is MANDATORY, it's thrown an exception saying: </p>
  
  <pre><code>org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:339)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:262)
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:101)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
      ...
  </code></pre>
  
  <p>If it's NOT_SUPPORTED, NEVER or SUPPORT, select queries work fine, but I get the same RollbackException if I try to execute a create, update or delete query.</p>
  
  <p>I've debugged the select queries, and before they throw the RollBackException, the query gets the result fine, and the exception is thrown just at the end of the function. In adition, if I get the Entities with find() of EntityManager and the service method doesn't have the @Transactional anotation, works fine, but if I make it transactional, it crashes with the same exception.</p>
  
  <p>This happens with all entities I have, but I use that to explain the problem.</p>
  
  <p>I think there is something wrong with my Spring configuration, but I don't know what.</p>
  
  <p>This is the full trace of the exception (In some lines there are references to AuthenticationSuccessHandler class, because it's where I call to the service class from):</p>
  
  <pre><code>WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception
  org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException: Transaction marked for rollback.
      at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:845)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:662)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:632)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:314)
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
      at com.citius.reservas.service.service$$EnhancerByCGLIB$$37b50d4.tryJPAFind(&lt;generated&gt;)
      at com.citius.reservas.AuthenticationSuccessHandlerImpl.onAuthenticationSuccess(AuthenticationSuccessHandlerImpl.java:47)
      ...
  Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
      at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:428)
      at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
      at com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:208)
      at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:842)
      ... 45 more
  </code></pre>
  
  <p>I have the following entity:</p>
  
  <pre><code>@Entity
  @Table(name = "roles", catalog = "reservas")
  @XmlRootElement
  public class Role implements Serializable {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Integer id;
  
      @NotNull
      @Size(min = 1, max = 50)
      private String name;
  
      private static final long serialVersionUID = 1L;
  </code></pre>
  
  <p>GenericRepository, a general class, which is implemented by all the repositories:</p>
  
  <pre><code>public class GenericRepositoryImpl&lt;T&gt; implements GenericRepository&lt;T&gt; {
  
      @PersistenceContext
      private EntityManager em;
  
      private Class&lt;T&gt; type;
  
      public GenericRepositoryImpl( ){
          Type t = getClass().getGenericSuperclass();
          ParameterizedType pt = (ParameterizedType) t;
          type = (Class) pt.getActualTypeArguments()[0];
      }
  
      @Override
      public T find(Object pk) {
          try{
              return em.find(type, pk);
          }catch(java.util.NoSuchElementException ex){
              return null;
          }
      }
  
      @Override
      public T create(T t) {
          em.persist(t);
          em.flush();
          em.refresh(t);
          return t;
      }
  
      @Override
      public List&lt;T&gt; query(Query q) {
          List&lt;T&gt; list= q.getResultList();
          if(list==null)
              list=new ArrayList&lt;T&gt;();        
          return list;
      }
  }
  </code></pre>
  
  <p>This is the role repository:</p>
  
  <pre><code>@Repository
  public class RoleRepositoryImpl extends GenericRepositoryImpl&lt;Role&gt; 
      implements RoleRepository{
  
      @PersistenceContext
      private EntityManager em;
  
      @Override
      public Role findByName(String name) {
          Query q = (Query) this.em.createNamedQuery("Role.findByName");
          q.setParameter("name", name);
          Role r = (Role) q.getSingleResult();
          return r;
      }
  
      @Override
      public List&lt;Role&gt; findAll() {
          Query q = (Query) this.em.createNamedQuery("Role.findAll");
          return this.query(q);
      }
  }
  </code></pre>
  
  <p>The Service class:</p>
  
  <pre><code>@Service
  public class service {
  
      @Autowired
      private RoleRepository roleRepository;
  
      @Transactional
      //This throws a RollBackException
      public void tryJPAEmpty(){
  
          roleRepository.findByName("example");
      }
  
      //This doesn't
      public Role tryJPAFind(){
          return roleRepository.find(new Integer(1));
      }
  }
  </code></pre>
  
  <p>Spring configuration (applicationContext.xml) is:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:context="http://www.springframework.org/schema/context"
         xmlns:jpa="http://www.springframework.org/schema/data/jpa"
         xmlns:tx="http://www.springframework.org/schema/tx" 
         xmlns:jee="http://www.springframework.org/schema/jee"
         xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
  "&gt;
      &lt;context:component-scan base-package="com.***.***" /&gt;
  
      &lt;jpa:repositories base-package="com.***.***.repositories" /&gt;
  
      &lt;tx:annotation-driven /&gt;
      &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt;
      &lt;context:annotation-config /&gt;
  
      &lt;beans&gt;
          &lt;bean id="EntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"&gt;
              &lt;property name="persistenceUnitName" value="JPAReservas"/&gt;
          &lt;/bean&gt;
  
          &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/&gt;
  
          &lt;bean id="transactionManager" 
              class="org.springframework.transaction.jta.JtaTransactionManager" &gt;
              &lt;property name="allowCustomIsolationLevels"&gt;
                  &lt;value&gt;true&lt;/value&gt;
              &lt;/property&gt;
          &lt;/bean&gt;
      &lt;/beans&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p>Persistence.xml (I have a data source and a connection pool created in my GlassFish server):</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
  http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt;
  
    &lt;persistence-unit name="JPAReservas" transaction-type="JTA"&gt;
      &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt;
      &lt;jta-data-source&gt;Reservas_mysql&lt;/jta-data-source&gt;
  
      &lt;!--Named queries--&gt;
      &lt;mapping-file&gt;META-INF/mapping/Role.xml&lt;/mapping-file&gt;
  
      &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;
    &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>
  
  <p>And finally, I have named queires in a xml file, like that:
          
              SELECT r FROM Role r
          </p>
  
  <pre><code>    &lt;named-query name="Role.findByName"&gt;
          &lt;query&gt;SELECT r FROM Role r WHERE r.name = :name&lt;/query&gt;
      &lt;/named-query&gt;
  </code></pre>
  
  <p>I'm really noob with Spring and JPA, so if you know some improvements, or changes I can do, please tell me.</p>