Java之:事务

一、文章来由

事务在金融领域用的是非常之多的,所以现在非常重要,比如一个事务是“A给B转账500块”,但这个步骤至少有:

(1)扣除A的500
(2)增加B的500

如果这两部分不是一起完成,就会有资损发生。

二、什么是事务

事务指的是逻辑上的一组操作,这组操作要么全部成功,要么全部失败。

一般的事务指的都是数据库事务,但是广义事务的定义不局限于数据库事务。

三、事务的特性

事务有4大特性,即 ACID。

ACID,指数据库事务正确执行的四个基本要素的缩写。包含:原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)。一个支持事务(Transaction)的数据库,必需要具有这四种特性,否则在事务过程(Transaction processing)当中无法保证数据的正确性,交易过程极可能达不到交易方的要求。

1、原子性

事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。

2、一致性

事务前后数据的完整性必须保证一致

比如还是刚刚A给B转账的例子,那么A给B转账结束后,总金额不变。

3、隔离性

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

隔离性非常重要,如果不考虑隔离性,就可能发生:脏读、不可重复读、幻读的问题

(1)脏读

一个事务读取了另一个事务改写但还未提交的数据,如果这些数据被回滚,则读到的数据无效。

这里写图片描述

(2)不可重复读

在同一事务中,多次读取同一数据返回的结果不同。

这里写图片描述

(3)幻读

一个事务读取了几行记录后,另一个事务插入一些记录。后来的查询中,第一个事务就会发现有些原来没有的记录。

这里写图片描述

当然,这些问题是有办法避免的,有隔离级别来限制,后面做解释。

4、持久性

一个事务一旦提交,它对数据库中的数据的改变就是永久性的,即使数据库发生故障也不应该对其有任何影响

四、事务的隔离级别(4种)

事务的隔离级别是为了防止脏读、不可重复读、幻读问题的发生,具体分成四种,如下:

这里写图片描述

Spring有一个default隔离级别,底层数据库用的哪个隔离级别,spring就用什么隔离级别
MySQL用的是repeatable_read
Oracle用的是read_committed

有一个更加直观的表格如下:

这里写图片描述

spring中的事务隔离级别配置如下:

这里写图片描述

五、事务的传播行为(7种)

首先要清楚的是:事务是因为有业务需求,才产生的一种机制。
所以事务的配置应该安放在业务层
比如还是刚刚那个转钱的例子:

这里写图片描述

如果aaa()和 bbb()方法需要用事务来解决,应该如何处理他们之间的关系呢?
这就需要用事务的传播行为来定义了

事务的传播行为详见下表:

这里写图片描述

其实这7种行为看起来很多,但是实则可以就分为3类:

(1)第一类 required:在当前事务中解决问题

(2)第二类 requires_new:挂起当前事务,简单来说就是隔离
这里写图片描述

思考:

为什么取流水号和打印日志需要用requires_new?

这主要有两个原因:
① 为了取号速度,取号是事务的第一步,因为如果不新建一个事务,取号需要加锁,如果这个事务比较长,就需要一直占着锁,这样就很慢。

② 既然是隔离,就是说取号和真正的事务处理不发生影响。这个原因也造成了一个结果,流水号有“作废”机制,也就是说万一发生异常,这个流水号也生成了,后面的会跳号。事务间就没有依赖关系了,会产生四种情况

(3)第三类 nested:嵌套事务

也就是说:
Required 操作在同一个事务里面
New aaa() 和 bbb() 不在一个事务中

这里写图片描述

这里写图片描述

spring的事务传播配置如下:

这里写图片描述

六、Spring事务管理

Spring事务管理配置详见:http://blog.csdn.net/hjm4702192/article/details/17277669

这里写图片描述

这里写图片描述

6.1 Spring事务配置方式

这里写图片描述

这里写图片描述

6.2 Spring事务接口

这里写图片描述

这里写图片描述

编程式的事务管理

这里写图片描述

为什么叫编程式的事务管理,就是需要编程实现,具体如下,使用匿名内部类

这里写图片描述

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: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:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置业务层类 -->
    <bean id="accountService" class="com.wanghubill.AccountServiceImpl">
        <property name="accoutDao" ref="accountDao" />
        <!-- 注入事务管理的模板 -->
        <property name="transactionTemplate" ref="transactionTemplate" />
    </bean>

    <!-- 配置DAO类 -->
    <bean id="accountDao" class="com.wanghubill.AccoutDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务管理类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务管理的模板:spring为了简化事务管理的代码而提供的类 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
        <property name="transactionManager" ref="transactionManager" />
    </bean>

</beans>

AccountService.java

package com.wanghubill;

/**
 * @author hupo.wh
 *
 */
public interface AccountService {

    /**
     * 
     * @param out
     * @param in
     * @param money
     */
    public void transfer(String out, String in, Double money);
}

AccountServiceImpl.java

package com.wanghubill;


import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author hupo.wh
 *
 */

public class AccountServiceImpl implements AccountService {

    private AccountDao accoutDao;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    //注入事务管理的模板
    private TransactionTemplate transactionTemplate;

    public void setAccoutDao(AccountDao accoutDao) {
        this.accoutDao = accoutDao;
    }

    public void transfer(final String out, final String in, final Double money) {

        System.out.println("enter transfer()");

//      accoutDao.outMoney(out, money);
//      //int i=1/0;
//      accoutDao.inMoney(in, money);

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accoutDao.outMoney(out, money);
                int i=1/0;
                accoutDao.inMoney(in, money);
            }
        });
    }

}

AccountDao.java

package com.wanghubill;

/**
 * @author hupo.wh
 *
 */

public interface AccountDao {

    void outMoney(String out, Double money);

    void inMoney(String in, Double money);
}

AccoutDaoImpl.java

package com.wanghubill;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccoutDaoImpl extends JdbcDaoSupport implements AccountDao {

    public void outMoney(String out, Double money) {

        String sql = "update account set money = money - ? where name = ?";
        this.getJdbcTemplate().update(sql,money,out);
    }

    public void inMoney(String in, Double money) {

        String sql = "update account set money = money + ? where name = ?";
        this.getJdbcTemplate().update(sql,money,in);
    }

}

声明式的事务管理

spring 声明式的事务管理是基于aop实现的。

注意用的时候要用代理对象,因为代理对象才是增强原对象的对象。

(1)声明式事务管理方式一:基于TransactionProxyFactoryBean的方式
这里写图片描述

这里写图片描述

缺点:为每一个需要事务管理的类配置事务管理器。

因为声明式事务管理都是非侵入性的(不用修改原代码),只用配置,所以就不帖源代码了

<?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:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置业务层类 -->
    <bean id="accountService" class="com.wanghubill.xml1tfb.AccountServiceImpl">
        <property name="accountDao" ref="accountDao" />
    </bean>

    <!-- 配置DAO类 -->
    <bean id="accountDao" class="com.wanghubill.xml1tfb.AccoutDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务管理类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置业务层代理 -->
    <bean id="accountServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" >
        <!-- 配置目标对象(增强对象) -->
        <property name="target" ref="accountService" />
        <!-- 注入事务管理器 -->
        <property name="transactionManager" ref="transactionManager" />
        <!-- 注入事务属性 -->
        <property name="transactionAttributes" >
            <props>
                <prop key="transfer">PROPAGATION_REQUIRED</prop>
            </props>
        </property>
    </bean>

</beans>

(2)声明式事务管理方式二:基于AspectJ的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:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置业务层类 -->
    <bean id="accountService" class="com.wanghubill.xml2aspectj.AccountServiceImpl">
        <property name="accountDao" ref="accountDao" />
    </bean>

    <!-- 配置DAO类 -->
    <bean id="accountDao" class="com.wanghubill.xml2aspectj.AccoutDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务管理类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务的通知(事务的增强) -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 哪些方法需要执行事务,怎么执行 -->
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置切面 -->
    <aop:config>
        <!-- 配置切入点 -->
        <!-- execution(* com.wanghubill.xml2aspectjaspectj.AccountService+.*(..)) -->
        <!-- execution(任意返回值 代理类+子类.*任意方法(..任意参数)) -->
        <aop:pointcut id="pointcut1" expression="execution(* com.wanghubill.xml2aspectj.AccountService+.*(..))" />
        <!-- 配置切面 -->
        <!-- 对pointcut1配置txAdvice增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1" />
    </aop:config>

</beans>

(3)声明式事务管理方式三:基于注解的方式

这里写图片描述

这里写图片描述

这里写图片描述

基于注解的方式,配置十分简单,只需在业务层需要事务的类上面打上注解

/AccountServiceImpl.java
package com.wanghubill.xml3notation;

import org.springframework.transaction.annotation.Transactional;

/**
 * @author hupo.wh
 *
 */

@Transactional
public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;


    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void transfer(final String out, final String in, final Double money) {

        System.out.println("enter transfer()");

        accountDao.outMoney(out, money);
        //int i=1/0;
        accountDao.inMoney(in, money);

    }

}
<?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:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置c3p0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置业务层类 -->
    <bean id="accountService" class="com.wanghubill.xml3notation.AccountServiceImpl">
        <property name="accountDao" ref="accountDao" />
    </bean>

    <!-- 配置DAO类 -->
    <bean id="accountDao" class="com.wanghubill.xml3notation.AccoutDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务管理类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

小结

注解和声明对比:
注解简单
声明是非侵入式

感悟:但是本质都是告诉框架,哪些类需要被代理来执行事务。

补充:

这里写图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值