Spring初级:声明式事务

87 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第34天,点击查看活动详

Spring中的事务

Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。

编程式事务管理

  • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
  • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

声明式事务管理

  • 一般情况下比编程式事务好用。
  • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
  • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

事务增强

  • 给配置文件导入事务的名称空间

     xmlns:tx="http://www.springframework.org/schema/tx"
    
     xsi:schemaLocation=" http://www.springframework.org/schema/tx
    
     [http://www.springframework.org/schema/tx/spring-tx.xsd"](http://www.springframework.org/schema/tx/spring-tx.xsd%22)
    
  • 导入spring-tx包。

  • 配置事务详情,包含事务隔离级别、是否只读、超时时间等。

     <tx:advice id="" transaction-manager="">
         <tx:attributes>
                 <tx:method name=""/>
         </tx:attributes>
     </tx:advice>
    
  • transaction-manager属性引用事务管理器对象

  • tx:method元素定义相关方法的事务配置,属性有:

     name:必须的,指定方法名,可使用*通配符。
    
     propagation:指定事务传播行为,指在两个业务之间如何共享事务。默认:REQUIRED
    
     read-only:只读事务,默认false
    
     rollback-for:触发回滚的异常定义。默认RuntimeException回滚
    
     isolation:指定事务的隔离级别。指并发事务之间的隔离关系。
     
    

事务传播行为

tx:method元素的propagation属性指定事务的传布行为,默认为REQUIRED,常用值有:

  • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
  • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
  • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

事务的回滚

tx:method元素的rollback-for属性指定事务的回滚条件。默认RuntimeException异常会回滚事务;可通过修改rollback-for属性值改变回滚条件:例:rollback-for="IOException,SQLException"

实现步骤

搭建数据库环境

    CREATE TABLE `user` (  
    `id` int(20NOT NULL,  
    `name` varchar(30DEFAULT NULL,  
    `pwd` varchar(30DEFAULT NULL,   PRIMARY KEY (`id`) 
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String name;
    private String pwd;
}

创建持久层访问接口

public interface UserMapper {
    //查询
    List<User> selectUser();

    //添加用户
    int addUser(User user);

    //删除
    int deleteUser(int id);
}

创建持久层接口的实现类

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
    //我们的所有操作,都是使用sqlSession来执行在原来,现在使用sqlSessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    //查询
    @Override
    public List<User> selectUser() {

        User user=new User(6,"小李","4123");

        UserMapper mapper=getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(5);
        return mapper.selectUser();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }

}

编写全局Mybatis配置文件

<?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>
    
    <typeAliases>
        <package name="com.zhao.pojo"/>
    </typeAliases>

</configuration>

编写全局Spring配置文件

<?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/aop" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <import resource="spring-dao.xml" />

    <!--bean-->
    <bean id="userMapper" class="com.zhao.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

</beans>

创建Mapper对应的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zhao.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select  * from mybatis.user
    </select>

    <insert id="addUser" parameterType="user">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
    </delete>
</mapper>

编写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:context="http://www.springframework.org/schema/aop" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--DataSource 使用Spring的数据源替换Mybatis的配置  c3p0 dbcp druid
    这里使用Spring提供的JDBC
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
      </bean>

    <!-- sqlSessionFactory   -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:com/zhao/mapper/*.xml" />
    </bean>

    <!--SqlSessionTemplate 就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory 因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--        <constructor-arg ref="dataSource" />-->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--结合aop实现事务织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给那些方法配置事务-->
        <!--配置事务的传播特性  propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.zhao.mapper.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
    </aop:config>
</beans>

测试一下

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper=context.getBean("userMapper", UserMapper.class);
    for (User user : userMapper.selectUser()) {
        System.out.println(user);
    }

image.png