Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization

I've got an app running on Tomcat 7, using Spring, Mybatis, and .. Mybatis-spring.

Here's the setup for the DB and transactions in servlet-context.xml:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDS" />
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="mapperLocations" value="classpath*:maps/*.xml" />
      <property name="transactionFactory">
        <bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
      </property>  
</bean>
<mybatis:scan base-package="com.domain.dao.mappers" />
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

The error I'm getting when I run a method that uses the SqlSession is the following:

org.springframework.dao.TransientDataAccessResourceException: SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization
    at org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:136)

What am I doing wrong?

My goal, really, is just to use transactions with this setup. I don't think I necessarilly need JTA. But if that's easy enough to setup on Tomcat, I'm willing to take a swing at it.

like image 204
Val Schuman Avatar asked Oct 21 '22 05:10

Val Schuman


2 Answers

And I solved the problem myself. Really simple solution. In case anyone runs into the same issue, all I needed to do is remove the following from the sqlSessionFactory bean:

<property name="transactionFactory">
      <bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
</property> 

I must have somehow entered it thinking I needed it, but apparently it's only needed if you're not using CMT (Container Managed Transactions).

like image 174
Val Schuman Avatar answered Oct 27 '22 22:10

Val Schuman


You can solve this by changing the transaction factory to

<property name="transactionFactory">
      <bean class="org.mybatis.spring.transaction.SpringManagedTransactionFactory" />
</property> 
like image 37
David Ruan Avatar answered Oct 28 '22 00:10

David Ruan