一、相关概念
1.1、事务
1.1.1、事务特性
原子性(acid):强调事务不可分割
一致性:事务的执行前后数据的完整性保持一致
隔离性:一个事物执行的过程中,不应该受到其他事物的干扰
持久性:事务一旦结束,数据就持久到数据库
1.1.2、事务的并发问题
脏读:一个事务读到了另一个事务的未提交的数据
不可重复读:一个事务读到了另一个事务已经提交的update的数据导致多次查询的结果不一致;
幻读/虚读:一个事务读到了另一个事务已经提交的insert的数据导致多次查询的结果不一致。
1.1.3、事务的隔离级别
1——读未提交:脏读、不可重复读、幻读都可能发生;
2——读已提交:避免脏读,但是不可重复读和幻读有可能发生;(Oracle默认)
4——可重复读:避免脏读和不可重复读,但是幻读有可能发生;(MySQL默认)
8——串行化:避免脏读、不可重复读、幻读。
1.2、Spring封装了事务管理代码
事务的操作有打开事务、提交事务、回滚事务
1.2.1、真正事务操作对象
因为在不同平台,操作事务的代码各不相同,Spring提供了一个接口PlatformTransactionManager
实现类: DataSourceTransactionManager (使用SpringJDBC或Mybatis进行持久化数据)
HibernateTransactionManager (使用Hibernate版本进行持久化数据时使用)
1.2.2、事务定义信息
即Spring管理事务的属性,分为:事务的隔离级别、是否只读、超时信息、事务的传播行为(Spring才有)
二、Spring管理事务的三种方式
已转账业务为例:
下面先模拟不加事务时的转账
先定义两个接口
ITransferDao
package com.zl.dao;
public interface ITransferDao {
void transferMoney(Integer id, Double money); //转钱
void receiptMoney(Integer id, Double money); //收钱
}
ITransferService
package com.zl.service;
public interface ITransferService {
void transfer(Integer from, Integer to, Double money);
}
两个接口的实现类
TransferDaoImpl
package com.zl.dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class TransferDaoImpl extends JdbcDaoSupport implements ITransferDao {
@Override
public void transferMoney(Integer id, Double money) { //转钱
getJdbcTemplate().update("update transfer set money=money-? where id=?",money,id);
}
@Override
public void receiptMoney(Integer id, Double money) { //收钱
getJdbcTemplate().update("update transfer set money=money+? where id=?",money,id);
}
}
TransferServiceImpl
package com.zl.service;
import com.zl.dao.TransferDaoImpl;
public class TransferServiceImpl implements ITransferService {
private TransferDaoImpl tdi;
public TransferDaoImpl getTdi() {
return tdi;
}
public void setTdi(TransferDaoImpl tdi) {
this.tdi = tdi;
}
@Override
public void transfer(Integer from, Integer to, Double money) {
//减钱
tdi.transferMoney(from, money);
// int d = 1/0; //模拟转钱过程中间可能会发生的异常
//加钱
tdi.receiptMoney(to, money);
}
}
连接数据库的属性文件
db.properties:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test
jdbc.user=root
jdbc.password=123456
Spring容器:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<!-- 指定Spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 1.连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 2.DAO-->
<bean name="tdi" class="com.zl.dao.TransferDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.Service -->
<bean name="transferservice" class="com.zl.service.TransferServiceImpl">
<property name="tdi" ref="tdi"></property>
</bean>
</beans>
测试
DemoTest.java
package com.zl.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.zl.service.ITransferService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DemoTest {
@Resource(name="transferservice")
private ITransferService its;
@Test
public void fun1() {
its.transfer(1, 2, 999.8d);
}
}
Junit测试后,数据库表更新后结果:
在TransferServiceImpl中添加下面的异常,再测试:
int d = 1/0;

id为1的money少了999.8,id为2的账户money并为增加,因为在此过程中发生了异常,转账过程中断了,这999.8“不翼而飞”,说明添加事务是必要的,下面介绍三种添加事务的方式。
准备工作:将核心事务管理器配置到Spring容器
<!-- 事务核心管理器,封装了所有事物的操作,依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
编码式
(编码式不是指的utf-8、gb2312这种编码,就是写代码的意思)在Spring容器(applicationContext.xml)中添加事务模板对象
然后将事务模板对象添加到Service里
最后applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<!-- 事务核心管理器,封装了所有事物的操作,依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!-- 指定Spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 1.连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 2.DAO-->
<bean name="tdi" class="com.zl.dao.TransferDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.Service -->
<bean name="transferservice" class="com.zl.service.TransferServiceImpl">
<property name="tdi" ref="tdi"></property>
<property name="tt" ref="transactionTemplate"></property>
</bean>
</beans>
TransferServiceImpl
package com.zl.service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import com.zl.dao.TransferDaoImpl;
public class TransferServiceImpl implements ITransferService {
private TransferDaoImpl tdi;
private TransactionTemplate tt;
public TransactionTemplate getTt() {
return tt;
}
public void setTt(TransactionTemplate tt) {
this.tt = tt;
}
public TransferDaoImpl getTdi() {
return tdi;
}
public void setTdi(TransferDaoImpl tdi) {
this.tdi = tdi;
}
@Override
public void transfer(Integer from, Integer to, Double money) {
tt.execute(new TransactionCallbackWithoutResult() { //excute事务的打开和关闭已经封装好了
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0) {
//减钱
tdi.transferMoney(from, money);
//加钱
tdi.receiptMoney(to, money);
}
});
}
}
Junit测试后,数据库表更新后结果:
加入int d=1/0; 发生了异常,但是数据库表刷新后,数据未改变!
XML配置(AOP)
(1)导包
4+2+connector+test+jdbc+aop+aspect+aop联盟+weaving织入
(2)导入新的约束
如果不清楚怎么导入约束的,可以参考我第二篇关于Spring的
一共四个命名空间
(3)配置通知
transfer方法还是最初的,不用添加任何事务代码
(4)配置将通知织入目标
applicationContext.xml最终为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 事务核心管理器,封装了所有事物的操作,依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 以后配置大量事务时,需要使用通配符配置增删改查 -->
<!-- 以方法为单位,指定方法应该有什么事务属性,isolation隔离级别,propagation传播行为,read-only是否只读 -->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="motified*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="get*"isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*"isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<!-- 本次需要 -->
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
</tx:attributes>
</tx:advice>
<!-- 配置织入 -->
<aop:config>
<aop:pointcut expression="excution(* com.zl.service.*ServiceImpl.*(..))" id="txpointcut"/>
<!-- 配置切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txpointcut"/>
</aop:config>
<!-- 指定Spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 1.连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 2.DAO-->
<bean name="tdi" class="com.zl.dao.TransferDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.Service -->
<bean name="transferservice" class="com.zl.service.TransferServiceImpl">
<property name="tdi" ref="tdi"></property>
<property name="tt" ref="transactionTemplate"></property>
</bean>
</beans>
注解配置(AOP)
(1)导包(同XML配置)
(2)导入约束(同XML配置)
(3)开启注解管理事务
不用配通知和事务,在编码式的基础上只用添加:
(4)使用注解(transfer方法上)
如果一个类中有很多个事务,可以把该注解放在类上!!!