在Spring+MyBatis組合中使用事務

   經過Spring和MyBatis的組合,給出一個較爲詳細的實例

 


  代碼清單:配置Spring+MyBatis測試環境
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
      http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--啓用掃描機制,並指定掃描對應的包-->
    <context:annotation-config/>
    <context:component-scan base-package="com.ssm.chapter13.*"/>

    <!-- 數據庫鏈接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="maxActive" value="255"/>
        <property name="maxIdle" value="5"/>
        <property name="maxWait" value="10000"/>
    </bean>

    <!-- 集成MyBatis -->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--指定MyBatis配置文件-->
        <property name="configLocation" value="classpath:ssm/chapter13/mybatis-config.xml"/>
    </bean>

    <!-- 事務管理器配置數據源事務 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 使用註解定義事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 採用自動掃描方式建立mapper bean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.chapter13"/>
        <property name="SqlSessionFactory" ref="SqlSessionFactory"/>
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    </bean>

</beans>

 


  代碼清單:POJO類——Role.java
package com.ssm.chapter13.pojo;

public class Role {
    private Long id;
    private String roleName;
    private String note;
}

 



  代碼清單:搭建MyBatis的RoleMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.chapter13.mapper.RoleMapper">

    <insert id="insertRole" parameterType="com.ssm.chapter13.pojo.Role">
        insert into t_role (role_name, note)
        values (#{roleName}, #{note})
    </insert>

</mapper>

 



  代碼清單:RoleMapper接口
package com.ssm.chapter13.mapper;

import com.ssm.chapter13.pojo.Role;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleMapper {
    public int insertRole(Role role);

}

 


  代碼清單:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 指定映射器路徑 -->
    <mappers>
        <mapper resource="ssm/chapter13/mapper/RoleMapper.xml"/>
    </mappers>
</configuration>

 



  代碼清單:操做角色的兩個接口
public interface RoleService {

    public int insertRole(Role role);

}

public interface RoleListService {

    public int insertRoleList(List<Role> roleList);

}

 



  代碼清單:兩個接口的實現類
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
    public int insertRole(Role role) {
        return roleMapper.insertRole(role);
    }

}

@Service
public class RoleListServiceImpl implements RoleListService {

    Logger log = Logger.getLogger(RoleListServiceImpl.class);

    @Autowired
    private RoleService roleService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public int insertRoleList(List<Role> roleList) {
        int count = 0;
        for (Role role : roleList) {
            try {
                count += roleService.insertRole(role);
            } catch (Exception ex) {
                log.info(ex);
            }
        }
        return count;
    }
}

 



  代碼清單:測試隔離級別和傳播行爲——Chapter13Main.java
public class Chapter13Main {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter13/spring-cfg.xml");
        RoleListService roleListService = ctx.getBean(RoleListService.class);
        List<Role> roleList = new ArrayList<Role>();
        for (int i = 1; i <= 2; i++) {
            Role role = new Role();
            role.setRoleName("role_name_" + i);
            role.setNote("note_" + i);
            roleList.add(role);
        }
        int count = roleListService.insertRoleList(roleList);
        System.out.println(count);
    }

}
  因爲保存點技術並非每個數據庫都能支持的,因此當你把傳播行爲設置爲NESTED時,Spring會先去探測當前數據庫是否可以支持保存點技術。若是數據庫不予支持,它就會和REQUIRES_NEW同樣建立新事務去運行代碼,以達到內部方法發生異常時並不回滾當前事務的目的。 文章來源:ssm13.6 
相關文章
相關標籤/搜索