spring笔记-10 事务管理

Spring中的事务管理

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

编程式事务管理

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

声明式事务管理

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

事务

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

事务四个属性ACID:

原子性(atomicity)

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

一致性(consistency)

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

隔离性(isolation)

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

持久性(durability)

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

例如写错一句sql语句
在这里插入图片描述
并在实现类中连续实现这两个sql语句,但是最终结果是插入成功,但删除失败,插入并且被提交上去了,这就违背了事物的原则.

使用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">

JDBC事务

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource" /> 
</bean>

配置好事务管理器后我们需要去配置事务的通知

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

spring事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行
为:
propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这
个事务中,这是最常见的选择。
propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与
propagation_required类似的操作
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的
调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3
个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!

package com.lx.dao;

import com.lx.pojo.Wife;

import java.util.List;

public interface WifeMapper {

    List<Wife> selectWife();

    int addWife(Wife wife);

    int deleteWife(String name);

}

<?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.lx.dao.WifeMapper">
    <select id="selectWife" resultType="com.lx.pojo.Wife">
        select * from mybatis.wife
    </select>

    <insert id="addWife" parameterType="com.lx.pojo.Wife">
        insert into mybatis.wife (name,sentence) values (#{name},#{sentence});
    </insert>

    <delete id="deleteWife" parameterType="String">
        delete from mybatis.wife where name=#{name}
    </delete>

</mapper>
package com.lx.pojo;

public class Wife {

    private String name;
    private String sentence;

    public Wife(String name, String sentence) {
        this.name = name;
        this.sentence = sentence;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSentence() {
        return sentence;
    }

    public void setSentence(String sentence) {
        this.sentence = sentence;
    }


    @Override
    public String toString() {
        return "Wife{" +
                "name='" + name + '\'' +
                ", sentence='" + sentence + '\'' +
                '}';
    }


}

package com.lx.dao;

import com.lx.pojo.Wife;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class WifeMapperImpl extends SqlSessionDaoSupport implements WifeMapper{
    public List<Wife> selectWife() {
        WifeMapper mapper = getSqlSession().getMapper(WifeMapper.class);
        List<Wife> wives = mapper.selectWife();


        Wife wife = new Wife("ceshi", "不能让事务不一致");
        mapper.addWife(wife);
        mapper.deleteWife("ceshi");

        return wives;
    }

    public int addWife(Wife wife) {
        WifeMapper mapper = getSqlSession().getMapper(WifeMapper.class);
        int i = mapper.addWife(wife);
        return i;

    }

    public int deleteWife(String name) {
        WifeMapper mapper = getSqlSession().getMapper(WifeMapper.class);
        return mapper.deleteWife(name);

    }
}

三组配置文件:

<?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.lx.pojo"/>
    </typeAliases>
    
    
</configuration>
<?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:context="http://www.springframework.org/schema/context"
       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/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


    <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>

    <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/lx/dao/*.xml"/>
    </bean>


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

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

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

</beans>
<?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
        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 id="wifeMapper" class="com.lx.dao.WifeMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>


</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值