Spring实现事务管理

学习目标:

Spring事务管理的实现


学习内容:

Spring的事务管理方法


学习时间:


学习产出:

事务

事务:在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。

事务ACID原则:

  • 原子性(Atomicity):是指一个事务要么全部执行,要么不执行,也就是说一个事务不可能只执行了一半就停止了
  • 一致性(Consistency):是指事务的运行并不改变数据库中数据的一致性。例如,完整性约束了a+b=10,一个事务改变了a,那么b也应该随之改变。
  • 隔离性(Isolation):是指两个以上的事务不会出现交错执行的状态。因为这样可能会导致数据不一致,更加具体的来讲,就是事务之间的操作是独立的。
  • 持久性(Durability):指事务执行成功以后,该事务对数据库所作的更改便是持久的保存在数据库之中,不会无缘无故的回滚。

1、搭建环境,初步测试

  • XML

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

    <import resource="application.xml"/>

    <bean id="UserMapper" class="com.spring.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="SqlSessionFactory"/>
    </bean>
</beans>

application.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="tmj20000509"/>
    </bean>

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

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="SqlSessionFactory"/>
    </bean>
</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>
        <typeAlias type="com.spring.pojo.User" alias="user"/>
    </typeAliases>

</configuration>
  • mapper

UserMapper

package com.spring.mapper;

import com.spring.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

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

    public int addUser(@Param("user") User user);

    public int deleteUser(int id);
}

UserMapper.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.spring.mapper.UserMapper">
    <select id="getUser" resultType="User">
        select * from user;
    </select>

    <!--故意写错语句用来测试事务提交-->
    <insert id="addUser" parameterType="User">
        insert into user (id,name,pwd) values (#{user.id},#{user.name},#{user.pwd});
    </insert>

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

UserMapperImpl

package com.spring.mapper;

import com.spring.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

/**
 * @ClassName UserMapperImpl
 * @Author $童一
 * @Description $
 * @Param $
 * @return $
 * @Date $ $
 **/

public class UserMapperImpl extends SqlSessionDaoSupport  implements UserMapper{

    @Override
        public List<User> getUser() {
            User user = new User(7, "张三李四", "12312321");
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            //将addUser和deleteUser写在这里是为了保证在同一个事务中,写在Test中就不是同一个事务了。
            mapper.addUser(user);
            mapper.deleteUser(7);
            return mapper.getUser();
    }

    @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);
    }
}
  • Test
    public void getUserTest2() throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = context.getBean("UserMapper",UserMapper.class);
        for (User users : mapper.getUser()) {
            System.out.println(users);
        }

    }

在数据库中查询,发现User(7, “张三李四”, “12312321”)已经插入进去
delete语句控制台报错语句错误


2、声明式事务管理:AOP应用

(1)XML实现事务管理
  • XML

application.xml

修改application.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">

    <!--    &lt;!&ndash;指定要扫描的包,这个包下的注解就会生效&ndash;&gt;-->
    <!--    <context:component-scan base-package="com.spring"/>-->
    <!--    <context:annotation-config/>-->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="tmj20000509"/>
    </bean>

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

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="SqlSessionFactory"/>
    </bean>

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


    <!--2、结合AOP进行事务织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性(一共七种):new propagation(默认)-->
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="select*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>


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

</beans>
  • mapper

mapper中都不改变

  • Test
@Test
    public void getUserTest2() throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = context.getBean("UserMapper",UserMapper.class);
        for (User users : mapper.getUser()) {
            System.out.println(users);
        }
    }

运行报错delete语句错误且add语句没有插入一个user


(2)注解实现事务管理
  • XML

application.xml
修改application.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"
       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/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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

        <!--指定要扫描的包,这个包下的注解就会生效-->
        <context:component-scan base-package="com.spring"/>
        <context:annotation-config/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="tmj20000509"/>
    </bean>

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

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="SqlSessionFactory"/>
    </bean>

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

    <!--2、注解实现事务切入-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
  • mapper

UserMapperImpl

UserMapperImpl中添加@Transactional注解

public class UserMapperImpl extends SqlSessionDaoSupport  implements UserMapper{

    @Override
    @Transactional
    public List<User> getUser() {
        User user = new User(7, "张三李四", "12312321");
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        //将addUser和deleteUser写在这里是为了保证在同一个事务中,写在Test中就不是同一个事务了。
        mapper.addUser(user);
        mapper.deleteUser(5);
        return mapper.getUser();
    }

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

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

运行报错delete语句错误且add语句没有插入一个user,成功使用注解实现事务管理

3、编程式事务:在代码中进行事务的管理

编程式事务由于需要在代码中添加try catch语句进行抛出代码可读性较差一般不使用

4、总结

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的问题
  • 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务
  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值