Spring事务管理(五)

1.什么是事务?

对数据库的一系列操作中,保证同时成功或者同时失败,不能出现部分成功,部分失败的情况。而这一系列操作称为数据库额的事务。

2.事务的特性

原子性:指事务是一个不可分割的工作单位,事务的操作要么都发生,要么都不发生。

一致性:事务前后的数据的完整性必须保持一致。

隔离性:指多个用户并发访问数据库时,一个用户的事务不能被其他用户的事务干扰,多个并发之间的数据相互隔离。

持久性:指一个事务一旦被提交,它对数据库中数据的改变是永久的,接下来即使数据库发生故障也不应该对其产生任何的影响。

3.事务的隔离级别

使用java操作的时候设置隔离级别由高到低分别为:

Serializable:可避免脏读、不可重复读、虚读情况的发生。

Repeatable read:可避免脏读、不可重复读情况发生。(可以重复读)

Read committed:可避免脏读的情况发生。(读已提交)。

Read uncommitted:最低级别,以上情况均为无法保证(读未提交的)。

脏读:指一个事务读取到了另一个事务未提交的数据。

不可重复读:在一个事务内读取表中某一行数据,多次读取结果不同(一个事务读取到另一个事务提交的数据)。

虚读:是指一个事务内读取到了别的事务插入的数据,导致前后数据不一致。

注意:大多数数据库默认的事务级别是Read committed,比如SqlServer Oracle。MySQL的默认隔离级别Repeatable read。

4.Spring的事务控制管理器

        Spring提供的事务:PlatformTransactionManager其中提供了三个方法

        getTransaction(TransactionDefinition)---得到一个事务管理对象

                        TransactionDefinition事务描述者【对要操作的事务进行简单的设置】

commit()  提交事务

rollback() 事务回滚

根据dao层(持久层/数据访问层)使用的不同的框架PlatformTransactionManager 的主要实现类大致如下:

1.当使用JDBC和MyBatis进行数据持久化操作的情况:DataSourceTransactionManager类
 2.当使用Hibernate进行数据持久化操作的情况:HibernateTransactionManager类

5.具体事务管理操作【声明式事务管理】

声明式事务管理---不用写java代码,在Spring的配置文件中通过配置来设置事务管理。

1).基于xml方式的事务管理操作

(1)下载依赖包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- spring-jdbc -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- spring_tx -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- MyBatis依赖 -->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <!-- mybatis-spring 整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- mysql数据库驱动 -->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!--druid 阿里的连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.7</version>
    </dependency>

(2).创建mapper接口

import java.util.HashMap;

public interface TransferMapper {
    //加钱
    public void addMony(HashMap<String,Object> parms);
    //减钱
    public void lessMony(HashMap<String,Object> parms);

}

(3)配置映射文件

<?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.wangxing.demo1.mapper.TransferMapper">
    <update id="addMoney" parameterType="java.util.HashMap">
        update t_account set money=money+#{mymoney} where user_name=#{myname};
    </update>
    <update id="lessMoney" parameterType="java.util.HashMap">
        update t_account set money=money-#{mymoney} where user_name=#{myname};
    </update>
</mapper>

(4)编写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/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- 配置自动扫描包 -->
        <context:component-scan base-package="com.demo.service"></context:component-scan>
        <!--读取资源文件-->
        <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${mydriver}"></property>
            <property name="url" value="${myurl}"></property>
            <property name="username" value="${myusername}"></property>
            <property name="password" value="${mypassword}"></property>
        </bean>
        <bean class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="classpath:TransferMapper.xml"></property>
        </bean>
        <!-- 配置扫描数据库访问接口,创建数据库访问对象 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.demo.mapper"></property>
        </bean>
        <!--事务配置-->
        <!-- 事务配置-->
        <!-- 1.创建事务对象-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 配置数据源 -->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 2创建事务 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="transfer"/>
            </tx:attributes>
        </tx:advice>
        <!-- 通过aop将上面创建好的事物,作用到指定的业务方法中去 -->
        <aop:config>
            <aop:pointcut id="point" expression="execution(* com.demo.service.TransferService.transfer())"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="point"></aop:advisor>

        </aop:config>
</beans>

(5)创建业务处理类

import com.demo.mapper.TransferMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
@Service
public class TransferService {
    @Autowired
    private TransferMapper transferMapper;
    public void transfer(){
        HashMap<String, Object> liuneng;
        liuneng = new HashMap<String, Object>();
        liuneng.put("name", "张三");
        liuneng.put("age", 100);
        int i = 1/0;
        transferMapper.addMony(liuneng);
        HashMap<String, Object> zhaosi = new HashMap<String, Object>();
        zhaosi.put("name", "李四");
        zhaosi.put("age", 100);
        transferMapper.lessMony(zhaosi);
        System.out.println("事务添加成功");
    }
}

 (6)配置数据库链接资源文件

mydriver = com.mysql.jdbc.Driver
myurl = jdbc:mysql://127.0.0.1:3306/test
myusername = root
mypassword = 123456

(7)测试

import com.demo.service.TransferService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContextTwo.xml");
        TransferService transferService = ac.getBean("transferService", TransferService.class);
        transferService.transfer();
    }
}

 2).基于注解方式的事务管理操作

步骤同上需要更改(4)和(5)

(4)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/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
       <context:component-scan base-package="com.demo.service"></context:component-scan>
       <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${mydriver}"></property>
            <property name="url" value="${myurl}"></property>
            <property name="username" value="${myusername}"></property>
            <property name="password" value="${mypassword}"></property>
        </bean>
        <bean class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="classpath:TransferMapper.xml"></property>
        </bean>
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.demo.mapper"></property>
        </bean>
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

(5)Service添加注解

import com.demo.mapper.TransferMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
@Service
public class TransferService {
    @Autowired
    private TransferMapper transferMapper;
    @Transactional
    public void transfer(){
        HashMap<String, Object> liuneng;
        liuneng = new HashMap<String, Object>();
        liuneng.put("name", "张三");
        liuneng.put("age", 100);
        int i = 1/0;
        transferMapper.addMony(liuneng);
        HashMap<String, Object> zhaosi = new HashMap<String, Object>();
        zhaosi.put("name", "李四");
        zhaosi.put("age", 100);
        transferMapper.lessMony(zhaosi);
        System.out.println("事务添加成功");
    }
}

无奈源于不够强大

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值