天天看點

Spring與Mybatis組合使用事務

1、首先配置Spring與mybatis的spring-config.xml配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:property-placeholder ignore-resource-not-found="false" location="classpath:jdbc.properties"></context:property-placeholder>

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="springmybatis"></context:component-scan>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username1}"></property>
        <property name="password" value="${password}"></property>

        <property name="initialSize" value="${initialSize}"></property>
        <property name="maxActive" value="${maxActive}"></property>
        <property name="minIdle" value="${minIdle}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mappers/Role-mapper.xml"></property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="springmybatis.mappers"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
    </bean>

</beans>
           

2、在該配置檔案中添加事務配置

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
           

解釋:第一個bean是為了配置事務管理器,第二個tx:annotation是為了開啟事務

3、書寫一個mapper接口,用來操作資料庫\

@Repository
public interface RoleMapper {
//    @Select("select id,role_name as name,note from t_role where id = #{id}")
    public Role getRole(int id);
    @Insert("insert into t_role values(#{role.id},#{role.name},#{role.note})")
    public void insertRole(@Param("role") Role role);
}
           

4、接下來就是一個Service

@Service
@Transactional
public class RoleService {
    @Autowired
    RoleMapper mapper = null;
    @Autowired
    RoleMapper2 mapper2 = null;

    public void addOneRole(Role role,Role role2){
        mapper.insertRole(role);
//        mapper2.insertRole(role2);
    }

    public void addOneRole2(Role role){
        mapper2.insertRole(role);
    }
}
           

這裡要注意一下:如果将@Transactional配置給Service,那麼就說明了此時一個方法中就是一個事務,兩個方法會是兩個事務,這一點尤為重要,因為如果不注意這一點将會造成transaction的失效,部落客已經踩到了大坑,特此注意

5、編寫測試:

@Component
public class TestMain {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Logger logger = Logger.getLogger(TestMain.class);
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        Role role = new Role();
        role.setId(7);
        role.setName("李龍");
        role.setNote("李龍的描述");
        RoleService roleService = (RoleService)context.getBean("roleService");
        roleService.addOneRole(role,null);
        roleService.addOneRole2(null);
    }
}
           

這裡的TestMain你可以看做Controller,部落客通過實驗證明了,如果調用一個服務的兩個方法,那麼就是兩個事務,如果調用一個方法,那麼方法中的程式就會運作在一個事務裡!!!!!!!!!!

至此,事務已經使用成功了!!!!!!!!!