在Spring—+Mybatis組合中使用事務的簡單實例

實例目錄圖:
在這裏插入圖片描述
chapter13Spring-cfg.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: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.xsd
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx.xsd
                            http://www.springframework.org/schema/context
                            https://www.springframework.org/schema/context/spring-context.xsd">

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

    <!-- 數據庫連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
        <property name="username" value="root" />
        <property name="password" value="hjw19990825" />
        <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-config.xml -->
        <property name="configLocation" value="classpath:/Chapter13/mybatis/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="Chapter13" />
        <property name="SqlSessionFactory" ref="SqlSessionFactory" />
        <property name="annotationClass" value="org.springframework.stereotype.Repository" />
    </bean>

</beans>

Role.java

package Chapter13.pojo;

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public Role(){}
}

搭建MyBatis的映射文件,建立SQL和POJO的關係。

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="Chapter13.mapper.RoleMapper">
        <insert id="insertRole" parameterType="Chapter13.pojo.Role">
            insert into role(role_name,note) values (#{roleName},#{note})
        </insert>
    </mapper> 

配置一個接口去使用。
RoleMapper.java

package Chapter13.mapper;

import 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="Chapter13/sqlMapper/RoleMapper.xml" />
    </mappers>
</configuration>

這樣MyBatis部分的內容就配置完成了,接着配置一些服務類(Service)。對於服務類而言,在開發的過程中一般都堅持“接口+實現類”的規則,這有利於實現類的變化。這裏我定義了兩個接口。

RoleService.java

package Chapter13.service;

import Chapter13.pojo.Role;

public interface RoleService {
    public int insertRole(Role role);
}

RoleServiceList.java

package Chapter13.service;

import Chapter13.pojo.Role;

import java.util.List;

public interface RoleListService {
    public int insertRoleList(List<Role> roleList);
}

然後寫兩個實現類。

RoleServiceImpl.java

package Chapter13.service.impl;

import Chapter13.mapper.RoleMapper;
import Chapter13.pojo.Role;
import Chapter13.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper=null;

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

RoleListServiceImpl.java

package Chapter13.service.impl;

import Chapter13.pojo.Role;
import Chapter13.service.RoleListService;
import Chapter13.service.RoleService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleListServiceImpl implements RoleListService {
    @Autowired
    private RoleService roleService=null;
    Logger log=Logger.getLogger(RoleListServiceImpl.class);

    @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)+1;
            }catch (Exception ex){
                log.info(ex);
            }
        }
        return count;
    }
}

最後我們在編寫一個測試類來測試這些事務。

Chapter13Main.java

package Chapter13.main;

import Chapter13.pojo.Role;
import Chapter13.service.RoleListService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class Chapter13Main {
    public static void main(String[] args){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("chapter13Spring-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("role_note_"+i);
            roleList.add(role);
        }
        int count=roleListService.insertRoleList(roleList);
        System.out.println(count);
    }
}

運行結果:

......
DEBUG 2020-04-22 18:52:30,548 org.mybatis.spring.mapper.ClassPathMapperScanner: Creating MapperFactoryBean with name 'roleMapper' and 'Chapter13.mapper.RoleMapper' mapperInterface
DEBUG 2020-04-22 18:52:30,558 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
DEBUG 2020-04-22 18:52:30,565 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
DEBUG 2020-04-22 18:52:30,572 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory'
DEBUG 2020-04-22 18:52:30,579 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
DEBUG 2020-04-22 18:52:30,595 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
DEBUG 2020-04-22 18:52:30,601 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.aop.config.internalAutoProxyCreator'
DEBUG 2020-04-22 18:52:30,658 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'roleListServiceImpl'
DEBUG 2020-04-22 18:52:30,730 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'roleServiceImpl'
DEBUG 2020-04-22 18:52:30,732 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'roleMapper'
DEBUG 2020-04-22 18:52:30,782 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
DEBUG 2020-04-22 18:52:30,788 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
DEBUG 2020-04-22 18:52:30,835 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'transactionManager'
DEBUG 2020-04-22 18:52:30,869 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry: Creating shared instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
DEBUG 2020-04-22 18:52:30,954 org.springframework.transaction.support.AbstractPlatformTransactionManager: Creating new transaction with name [Chapter13.service.impl.RoleListServiceImpl.insertRoleList]: PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED
DEBUG 2020-04-22 18:52:31,782 org.springframework.jdbc.datasource.DataSourceTransactionManager: Acquired Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e] for JDBC transaction
DEBUG 2020-04-22 18:52:31,787 org.springframework.jdbc.datasource.DataSourceUtils: Changing isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e] to 2
DEBUG 2020-04-22 18:52:31,789 org.springframework.jdbc.datasource.DataSourceTransactionManager: Switching JDBC Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e] to manual commit
DEBUG 2020-04-22 18:52:31,791 org.springframework.transaction.support.AbstractPlatformTransactionManager: Suspending current transaction, creating new transaction with name [Chapter13.service.impl.RoleServiceImpl.insertRole]
DEBUG 2020-04-22 18:52:31,803 org.springframework.jdbc.datasource.DataSourceTransactionManager: Acquired Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] for JDBC transaction
DEBUG 2020-04-22 18:52:31,803 org.springframework.jdbc.datasource.DataSourceUtils: Changing isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to 2
DEBUG 2020-04-22 18:52:31,804 org.springframework.jdbc.datasource.DataSourceTransactionManager: Switching JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to manual commit
DEBUG 2020-04-22 18:52:31,811 org.mybatis.spring.SqlSessionUtils: Creating a new SqlSession
DEBUG 2020-04-22 18:52:31,818 org.mybatis.spring.SqlSessionUtils: Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76494737]
DEBUG 2020-04-22 18:52:31,828 org.mybatis.spring.transaction.SpringManagedTransaction: JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] will be managed by Spring
DEBUG 2020-04-22 18:52:31,837 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: insert into role(role_name,note) values (?,?) 
DEBUG 2020-04-22 18:52:31,888 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: role_name_1(String), role_note_1(String)
DEBUG 2020-04-22 18:52:31,892 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==    Updates: 1
DEBUG 2020-04-22 18:52:31,893 org.mybatis.spring.SqlSessionUtils: Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76494737]
DEBUG 2020-04-22 18:52:31,893 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76494737]
DEBUG 2020-04-22 18:52:31,894 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76494737]
DEBUG 2020-04-22 18:52:31,894 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76494737]
DEBUG 2020-04-22 18:52:31,894 org.springframework.transaction.support.AbstractPlatformTransactionManager: Initiating transaction commit
DEBUG 2020-04-22 18:52:31,894 org.springframework.jdbc.datasource.DataSourceTransactionManager: Committing JDBC transaction on Connection [org.apache.commons.dbcp.PoolableConnection@353352b6]
DEBUG 2020-04-22 18:52:31,897 org.springframework.jdbc.datasource.DataSourceUtils: Resetting isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to 4
DEBUG 2020-04-22 18:52:31,898 org.springframework.jdbc.datasource.DataSourceTransactionManager: Releasing JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] after transaction
DEBUG 2020-04-22 18:52:31,899 org.springframework.transaction.support.AbstractPlatformTransactionManager: Resuming suspended transaction after completion of inner transaction
DEBUG 2020-04-22 18:52:31,899 org.springframework.transaction.support.AbstractPlatformTransactionManager: Suspending current transaction, creating new transaction with name [Chapter13.service.impl.RoleServiceImpl.insertRole]
DEBUG 2020-04-22 18:52:31,900 org.springframework.jdbc.datasource.DataSourceTransactionManager: Acquired Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] for JDBC transaction
DEBUG 2020-04-22 18:52:31,900 org.springframework.jdbc.datasource.DataSourceUtils: Changing isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to 2
DEBUG 2020-04-22 18:52:31,900 org.springframework.jdbc.datasource.DataSourceTransactionManager: Switching JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to manual commit
DEBUG 2020-04-22 18:52:31,901 org.mybatis.spring.SqlSessionUtils: Creating a new SqlSession
DEBUG 2020-04-22 18:52:31,901 org.mybatis.spring.SqlSessionUtils: Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@710636b0]
DEBUG 2020-04-22 18:52:31,901 org.mybatis.spring.transaction.SpringManagedTransaction: JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] will be managed by Spring
DEBUG 2020-04-22 18:52:31,902 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: insert into role(role_name,note) values (?,?) 
DEBUG 2020-04-22 18:52:31,902 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: role_name_2(String), role_note_2(String)
DEBUG 2020-04-22 18:52:31,903 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==    Updates: 1
DEBUG 2020-04-22 18:52:31,903 org.mybatis.spring.SqlSessionUtils: Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@710636b0]
DEBUG 2020-04-22 18:52:31,903 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@710636b0]
DEBUG 2020-04-22 18:52:31,904 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@710636b0]
DEBUG 2020-04-22 18:52:31,904 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization: Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@710636b0]
DEBUG 2020-04-22 18:52:31,904 org.springframework.transaction.support.AbstractPlatformTransactionManager: Initiating transaction commit
DEBUG 2020-04-22 18:52:31,904 org.springframework.jdbc.datasource.DataSourceTransactionManager: Committing JDBC transaction on Connection [org.apache.commons.dbcp.PoolableConnection@353352b6]
DEBUG 2020-04-22 18:52:31,906 org.springframework.jdbc.datasource.DataSourceUtils: Resetting isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] to 4
DEBUG 2020-04-22 18:52:31,906 org.springframework.jdbc.datasource.DataSourceTransactionManager: Releasing JDBC Connection [org.apache.commons.dbcp.PoolableConnection@353352b6] after transaction
DEBUG 2020-04-22 18:52:31,907 org.springframework.transaction.support.AbstractPlatformTransactionManager: Resuming suspended transaction after completion of inner transaction
DEBUG 2020-04-22 18:52:31,907 org.springframework.transaction.support.AbstractPlatformTransactionManager: Initiating transaction commit
DEBUG 2020-04-22 18:52:31,907 org.springframework.jdbc.datasource.DataSourceTransactionManager: Committing JDBC transaction on Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e]
DEBUG 2020-04-22 18:52:31,908 org.springframework.jdbc.datasource.DataSourceUtils: Resetting isolation level of JDBC Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e] to 4
DEBUG 2020-04-22 18:52:31,908 org.springframework.jdbc.datasource.DataSourceTransactionManager: Releasing JDBC Connection [org.apache.commons.dbcp.PoolableConnection@28261e8e] after transaction
2

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章