Fork me on GitHub

.Spring的事务管理

Spring的事务管理

1.程序中的事务控制理解

1.1.事务的概念

事务是一组操作的执行单元,相对于数据库操作来讲,事务管理的是一组SQL指令,比如增加,删除,修改等,事务的一致性要求这个是屋内的操作必须全部执行成功,如果在此过程中出现了差错,比如一条SQL语句没有执行成功,那么这一组操作就将全部回滚,即返回到没有进行执行这组执行前的操作状态

事务的特性:ACID

  • Atomic:原子性,要么成功,要么都失败
  • Consistent:一致性,数据应该不被破坏
  • Isolate:隔离性,不同用户操作不会混淆
  • Durable:持久性,永久保存

事物的概念是数据库中的,但是在程java程序中也可以使用事务控制。

1.2.程序控制举例

在一个项目中经常遇到的一个流程是:用户访问-->Action处理请求-->Service调用dao层-->dao操作数据库获得数据

一个业务的成功:调用service是执行成功的,意味着service中调用的所有的dao是执行成功的,事务应该在service层统一控制

假设在service中调用了两次dao,但是第二次执行失败了,这个时候如果没有事务,就只有一部分数据被加入了数据库。如果使用了事务,就会回滚整个操作,这样代码执行有问题也不会对数据库有影响。

1.3.两种事务控制概述

1.编程式事务控制:
自己动手控制事务,就叫做编程式事务控制。
jdbc代码:

conn.setAutoCommite(false);//设置手动控制事务

Hibernate代码:

session.beginTransaction();//开启下一个事务

细粒度的事务控制:可以对指定的方法,指定的方法和某几行添加事务控制。
此方法比较灵活,但是开发起来比较繁琐:每次都要开启,提交,回滚

2.声明式事务控制:
Spring提供了对事务的管理,这个就叫声明式事务管理
Spring提供了对事务控制的实现,用户如果想用Spring的声明式事务管理,只需要在配置文件中配置即可。不想使用时直接移除配置。这个实现了对事务控制的最大程度的解耦。
Spring声明式事务管理,核心实现就是基于AOP

粗粒度的事务控制:只能给整个方法应用事务,不可以对方法的某几行应用事务。因为AOP拦截的是方法。不能只拦截方法里面的制定某几行

Spring声明式事务管理器类:
Jdbc技术:DataSourceTransactionManager
Hibernate技术:HibernateTransactionManager

2.声明式事务管理

2.1.XML方式实现

实现步骤:
1.引入spring-sop相关的4个jar文件
2.引入aop名称空间(xml配置方式需要引入)
3.引入tx名称空间(事务方式必须引入)

代码示例:
首先是一个部门对象Dept。然后是DeptDao对把一个Dept数据保存到数据库中的方法,再之后是通过DeptService层来调用DeptDao,注意DeptService调用两次DeptDao,第一次调用之后,模拟一个异常,这时,一个Service方法并没有执行完,如果没有事务,则执行了一次保存到数据库的操作,但是如果有事务,这个方法在出错的时候就回滚了,数据库中不会有数据插入。

先看Dept.java

public class Dept {
    private int deptId;
    private String deptName;

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}

操作数据库层DeptDao.java

/**
 * DAO的实现,使用Spring对jdbc的支持功能
 */
public class DeptDao {

    //容器注入jdbcTemplate对象
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }



    public void save(Dept dept){
        String sql = "insert into t_dept (deptName) values (?)";
        jdbcTemplate.update(sql,dept.getDeptName());

    }

}

调用DeptDao的DeptService.java

public class DeptService {
    //容器注入dao对象
    private DeptDao deptDao;

    public void setDeptDao(DeptDao deptDao) {
        this.deptDao = deptDao;
    }

    public void save(Dept dept){
        //第一次调用
        deptDao.save(dept);

        //产生异常
        int i = 1/0;//事务遇到异常会回滚

        //第二次调用
        deptDao.save(dept);

    }
}

以上是没有使用事务的时候,异常产生,有一条数据会保存到数据库。
在bean.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/c"
       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/tx
     	 http://www.springframework.org/schema/tx/spring-tx.xsd">



    <!--1.数据源对象,c3p0连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///db"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
        <property name="initialPoolSize" value="3"/>
        <property name="maxPoolSize" value="10"/>
        <property name="maxStatements" value="100"/>
        <property name="acquireIncrement" value="2"/>
    </bean>


    <!--2. 2. JdbcTemplate工具类实例-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!-- 3. dao实例 -->
    <bean id="deptDao" class="a_tx.DeptDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

    <!-- 4. service实例 -->
    <bean id="deptService" class="a_tx.DeptService">
        <property name="deptDao" ref="deptDao"/>
    </bean>


    <!--############# Spring声明式事务管理配置 ###################-->
    <!--5.1.配置事务管理器类-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--5.2.配置事务增强(如何管理事务?)-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!--5.3.AOP配置,拦截那些方法(切入点表示式)+应用上面的事务增强配置-->
    <aop:config>
        <aop:pointcut expression="execution(* a_tx.DeptService.save(..))" id="pt"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>
    
</beans>

此文件中的各种引入是最全的,可以再其他地方使用

2.2.注解方式实现

使用注解方式实现Spring的声明式事务管理,更加简单
实现步骤:
1.必须引入AOP相关的jar文件。

  • aopalliance.jar
  • aspectjrt.jar
  • aspectjweaver.jar
  • spring-aop-3.2.5.RELEASE.jar

2.bean.xml中指定注解方式声明事务管理以及应用的事务管理器类

3.在需要添加事务控制的地方,写上:@Transactional

@Transaction注解:
1.应用事务的注解
2.定义到方法上:是当前方法应用Spring的声明式事务
3.定义到类上:当前类中所有的方法都应用Spring声明式事务管理
4.定义到父类上:当执行父类的方法时候应用事务

示例代码:
1.操作的对象Dept没有改变
2.操作Dept的DeptDao中把DeptDao使用注解添加到容器,获取JdbcTemplate时,使用注解获取
DeptDao.java

/**
 * DAO的实现,使用Spring对jdbc的支持功能
 */
@Repository//把DeptDao加入容器
public class DeptDao {

    @Resource //获取容器对象
    private JdbcTemplate jdbcTemplate;


    public void save(Dept dept){
        String sql = "insert into t_dept (deptName) values (?)";
        jdbcTemplate.update(sql,dept.getDeptName());

    }

}

3.调用DeptDao的DeptService,也使用注解加入容器以及使用注解获取对象,最后在目标方法上使用注解添加事务
DeptService.java

@Service //DeptService加入容器
public class DeptService {


    //容器中获取对象
    @Resource
    private DeptDao deptDao;


    @Transactional //对该方法实行事务
    public void save(Dept dept){
        //第一次调用
        deptDao.save(dept);

        //产生异常
        int i = 1/0;//事务遇到异常会回滚

        //第二次调用
        deptDao.save(dept);

    }
}

bean.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/c"
       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">



<!--1.数据源对象,c3p0连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///db"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
        <property name="initialPoolSize" value="3"/>
        <property name="maxPoolSize" value="10"/>
        <property name="maxStatements" value="100"/>
        <property name="acquireIncrement" value="2"/>
    </bean>


    <!--2. 2. JdbcTemplate工具类实例-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--开启注解扫描-->
    <context:component-scan base-package="b_anno_test"/>

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


    <!--注解方式实现事务:指定注解实现事务-->
    <tx:annotation-driven transaction-manager="txManager"/>
    
</beans>

测试类:
App.java

/**
 * 测试类
 * Created by Administrator on 2017/1/17 0017.
 */
public class App {

    @Test
    public void testApp() throws Exception{
        //容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("b_anno_test/bean.xml");

        //模拟数据
        Dept dept = new Dept();
        dept.setDeptName("开发部2");
        DeptService deptService = (DeptService) ac.getBean("deptService");
        deptService.save(dept);

    }
}

2.3.事务属性

@Service //DeptService加入容器
public class DeptService {


    //容器中获取对象
    @Resource
    private DeptDao deptDao;


    //对该方法实行事务
    @Transactional (
            readOnly = false, //读写事务
            timeout = -1, //事务的超时时间不限制,这里的不限制是说事务上没有限制,但是最终还是要根据数据库底层来觉得
            noRollbackFor = ArithmeticException.class, //遇到数学异常不回滚
            isolation = Isolation.DEFAULT, //事务的隔离级别,此时是数据库的默认
            propagation = Propagation.REQUIRED //事务的传播行为
    )

    public void save(Dept dept){
        //第一次调用
        deptDao.save(dept);

        //产生异常
        int i = 1/0;//事务遇到异常会回滚

        //第二次调用
        deptDao.save(dept);

    }
}

事务的属性一共有五种,上面的代码已经列出,分别解释一下:

  • 只读状态,只读事务不修改任何数据,可以优化查询操作
  • -1表示不超时,最终由底层数据库系统决定
  • 事务超时,事务的最长持续时间,如果事务一直没有提交或者回滚,那么超出该时间后,系统将自动回滚事务,单位秒
  • 隔离级别,并发访问下数据库的安全性
  • 传播行为,定义关于客户端和被调用方法的事务边界

事务传播行为:
Propagation.REQUIRED
指定当前的方法必须在事务的环境下执行;
如果当前运行的方法,已经存在事务, 就会加入当前的事务;
Propagation.REQUIRED_NEW
指定当前的方法必须在事务的环境下执行;
如果当前运行的方法,已经存在事务: 事务会挂起; 会始终开启一个新的事务,执行完后; 刚才挂起的事务才继续运行。

posted @ 2017-01-18 10:26  洋葱源码  阅读(644)  评论(0编辑  收藏  举报