Spring的声明式事务


声明式事务

事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。

事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。(原子性)

事务四个属性ACID

原子性(atomicity)

事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用

一致性(consistency)

一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中

隔离性(isolation)

可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏

持久性(durability)

事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中


Spring中的事务管理

编程式事务管理

声明式事务管理(重点)

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

使用Spring管理事务,注意头文件的约束导入 : tx

xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

事务管理器

  • 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
  • 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。

模拟事务使用场景

新建实体类

User.class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;
    private String username;
    private String password;

}

接口

UserMapper (interface)

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

    public int add(User user);

    public int delete(int id);
}

接口配置

UserMapper.xml,这里故意在 delete 方法的 sql 语句中写错,制造 sql 异常

<?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.allen.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from user;
    </select>

    <insert id="add" parameterType="user">
        insert into user(`username`,`password`)values (#{username},#{password});
    </insert>

    <delete id="delete" parameterType="int">
        deletes from user where id=#{id};
    </delete>

</mapper>

接口 Mapper 实现类

UserMapperImpl,注意在 selectUser 调用时,方法调用顺序依次为: add – delete – selectUser

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    //sqlSession不用我们自己创建了,Spring来管理
    //原来使用的 sqlSession,现在统统换成 SqlSessionTemplate

    @Override
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.add(new User(17, "sg1", "566311"));
        mapper.delete(17);
        return mapper.selectUser();
    }

    @Override
    public int add(User user) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.add(user);

    }

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

spring-dao.xml

配置声明式事务

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

配置aop织入事务

    <!--配置aop织入事务-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性 propagation:如果没有事务,就新建一个事务-->
        <tx:attributes>
<!--            <tx:method name="add" propagation="REQUIRED"/>-->
<!--            <tx:method name="delete" propagation="REQUIRED"/>-->
<!--            <tx:method name="update" propagation="REQUIRED"/>-->
<!--            <tx:method name="selectUser" read-only="true"/>-->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

配置事务切入

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

完整代码 spring-dao.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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
       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">

<!--    DataSource:使用Spring的数据源替换Mybatis的配置  c3p0 dbcp druid
        这里使用Spring提供的jdbc: org.springframework.jdbc.datasource
-->
        <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/mybatis02?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="1005"/>
        </bean>

<!--    SqlSessionFactory-->
    <!--配置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/allen/mapper/*.xml"/>
        <!--        开启别名-->
        <!-- <property name="typeAliases" value="com.allen.pojo.User"/>-->
    </bean>

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

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

    <!--配置aop织入事务-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性 propagation:如果没有事务,就新建一个事务-->
        <tx:attributes>
<!--            <tx:method name="add" propagation="REQUIRED"/>-->
<!--            <tx:method name="delete" propagation="REQUIRED"/>-->
<!--            <tx:method name="update" propagation="REQUIRED"/>-->
<!--            <tx:method name="selectUser" read-only="true"/>-->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

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

</beans>

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>

    <!--    开启别名-->
    <typeAliases>
        <package name="com.allen.pojo"/>
    </typeAliases>

    <!--    设置-->
    <!--    <settings>-->
    <!--        <setting name="" value=""/>-->
    <!--    </settings>-->
</configuration>

applicationContext.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: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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

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

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

</beans>

测试

public class MyTest {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

}

输出

结果报错

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'deletes from user where id=17' at line 1

但数据库未添加成功!

若删除事务织入,则依然报错,但add方法调用成功。

更多Spring IOC、AOP、事务解析,参考
https://juejin.cn/post/6844904030745919495


文章作者: Hailong Gao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Hailong Gao !
评论
  目录