Reputation: 155
I am currently working on a project which has already implemented mybatis. Since this is a legacy code, the implementation is done using
Spring application context file
<bean id="sqlSessionFactory" class="com.ca.aa.ui.framework.common.mybatis.SqlSessionFactoryBeanWrapper">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:ibatis/*_mapper.xml" />
</bean>
There is another xml file referenced from application context
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" name="tenantDAO">
<property name="mapperInterface" value="com.ca.ias.data.dao.TenantDAO" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
TenantDAO.java
public interface TenantDAO {
public List<something> somemethod1();
}
Then there is an service layer which access the above java class adn then persists the object
<bean id="issuerService" class="com.ca.ias.admin.service.IssuerServiceImpl">
<property name="tenantDAO" ref="tenantDAO"/>
</bean>
there is a plain java method, which calls tenantDAO and then persists the object.
IssuerServiceImpl.java
public void insert(){
try{
tenantDao.insert();
}catch(Exception e){
}finally{
}
How do I implement transaction manager here, please help?
Upvotes: 1
Views: 9740
Reputation: 15861
The are many ways to do that especially given that you already have spring configured. Basically you need to configure two things
Transaction manager
You need to define transaction manager in your spring context. Depending on where dataSource
mentioned in your sqlSessionFactory
definition comes from it may vary. Most probably you use connection pool in your project that is you have configuration of some connection pool like this:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
If this is the case then you need to add configuration like this to you spring context
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
Transaction boundaries
The simplest way is to use annotation driven transaction demarcation.
Then you need enable it first:
<tx:annotation-driven transaction-manager="txManager"/>
With this configuration you can use Transactional
annotation to mark methods in your service:
@Transactional
public void insert(){
}
@Transactional(readOnly=true)
public void find(){
}
Upvotes: 1