事务回顾
- 事务的概念:事务是逻辑上一组操作,组成这组操作各个逻辑单元,要么一起成功,要么一起失败。
- 事务的特性:原子性;一致性;隔离性;持久性
- 事物并发引起一些读的问题:脏读;不可重复读;虚读(幻读)
- 解决读问题—设置事务隔离级别:read uncommitted;read committed;repeatable read;Serializable
Spring事务管理的API介绍
1、PlatformTransactionManager接口:是spring的平台事务管理器,它里面提供了我们常用的操作事务的方法,包含3个具体的操作:
- 获取事务状态信息:TransactionStatus getTransaction(TransactionDefinition definition)
- 提交事务:void commit(TransactionStatus status)
- 回滚事务:void rollback(TransactionStatus status)
2、开发中一般使用它的实现类:
- DataSourceTransactionManager:使用SpringJDBC和iBatis进行持久化数据时使用
- HibernateTransactionManager:使用Hibernate3.0版本进行持久化数据时使用(HibernateX.HibernateTransactionManager中的X是Hibernate的版本号)
- JpaTransactionManager:使用JPA进行持久化数据时使用
- JdoTransactionManager:当持久化机制是Jdo时使用
- JtaTransactionManager:使用JTA实现管理事务,在一个事务跨越多个资源时使用
3、真正管理事务的对象:
- org.springframework.jdbc.datasource.DataSourceTransactionManager(使用Spring JDBC或iBatis 进行持久化数据时使用)
- org.springframework.orm.hibernate3.HibernateTransactionManager(使用Hibernate版本进行持久化数据时使用)
4、TransactionDefinition是事务的定义信息对象,里面有如下方法:
- 获取事务对象名称:String getName()
- 获取事务隔离级别:int getIsolationLevel()
- 获取事务传播行为:int getPropagationBehavior()
- 获取事务超时时间:int getTimeout()
- 获取事务是否只读:boolean isReadOnly()(读写型事务:增、删、改时开启事务;只读型事务:查询时也会开启事务)
5、事务的隔离级别:
- ISOLATION_DEFAULT:默认级别,归属下面某一种
- ISOLATION_READ_UNCOMMITTED:能够读取到没有被提交的数据,这个级别的隔离机制无法解决脏读、不可重复读、幻读中的任何一种,因此很少使用
- ISOLATION_READ_COMMITTED:能够读到已提交的数据,自然能够防止脏读,但是无法限制不可重复读和幻读(Oracle默认级别)
- ISOLATION_REPEATABLE_READ:重复读取,即在数据读出来之后加锁,读取了一条数据,这个事务不结束,别的事务就不可以改这条记录,这样就解决了脏读、不可重复读的问题,但是幻读的问题还是无法解决
- ISOLATION_SERLALIZABLE:串行化,最高的事务隔离级别,不管多少事务,挨个运行完一个事务的所有子事务之后才可以执行另外一个事务里面的所有子事务,这样就解决了脏读、不可重复读和幻读的问题
6、事务的传播行为:
- REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
- REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
- SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
- MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER:以非事务方式运行,如果当前存在事务,抛出异常
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
7、超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
8、事务是否只读:建议查询时设置为只读。
9、TransactionStatus接口:某个时间点上事务对象的状态信息,包含以下6个具体的操作:
- 刷新事务:void flush()
- 获取是否存在存储点:boolean hasSavepoint()
- 获取事务是否完成:boolean isCompleted()
- 获取事务是否为新的事务:boolean isNewTransaction()
- 获取事务是否回滚:boolean isRollbackOnly()
- 设置事务回滚:void setRollbackOnly()
10、总结:Spring框架进行事务的管理,首先使用TransactionDefinition对事务进行定义。通过PlatformTransactionManager根据TransactionDefinition的定义信息进行事务的管理。在事务管理过程中产生一系列的状态:保存到TransactionStatus中。
基于xml的声明式事务控制
原理:AOP面向切面编程
- 创建项目,引入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- aop的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- jdbc模板 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
- 创建service层接口和实现类
public interface AccountService {
public void transfer(Long fromId,Long toId,Double money);
public Account findById(Long id);
}
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void transfer(Long fromId, Long toId, Double money) {
Account fromAccount = accountDao.findById(fromId);
Account toAccount = accountDao.findById(toId);
fromAccount.setMoney(fromAccount.getMoney() - money);
toAccount.setMoney(toAccount.getMoney() + money);
accountDao.update(fromAccount);
int a = 10 / 0;
accountDao.update(toAccount);
}
public Account findById(Long id) {
Account account = accountDao.findById(id);
/*
* 应该是只能做查询操作,但现在做了修改操作,是不被允许的.
* 怎么才能不允许在查询方法中,做增删改操作呢?给该方法加只读事务
*/
account.setMoney(100000.0);
accountDao.update(account);
return account;
}
}
- 创建dao层接口和实现类
public interface AccountDao {
public void save(Account account);
public void update(Account account);
public Account findById(Long id);
}
public class AccountDaoImpl implements AccountDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void save(Account account) {
jdbcTemplate.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
}
public void update(Account account) {
this.jdbcTemplate.update("UPDATE account SET name = ?,money = ? WHERE id = ?",account.getName(),account.getMoney(),account.getId());
}
public Account findById(Long id) {
Account account = this.jdbcTemplate.queryForObject("select * from account where id = ?", new AccountRowMapper(), id);
return account;
}
}
- 核心配置文件配置
<?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/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="accountService" class="com.ityang.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="com.ityang.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 配置jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- find开头的方法加只读事务 ,*表示通配符,匹配任意-->
<tx:method name="find*" read-only="true"/>
<!-- 其余方法是加可读写的事务 -->
<tx:method name="*"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<!-- 配置切入点表达式:告诉框架哪些方法要控制事务 -->
<aop:pointcut expression="execution(* com.ityang.service.impl.*.*(..))" id="pt"/>
<!--将定义好的事务属性应用到上述的切入点 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestTX {
@Autowired
private AccountService accountService;
@Test
public void test1(){
accountService.transfer(1L,2L,500.0);
}
@Test
public void test2(){
Account account = accountService.findById(1L);
System.out.println(account);
}
}
基于注解的声明式事务控制
- 创建项目,引入依赖(跟xml一样)
- 创建service和dao层接口和实现类(同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">
<!-- 开启spring注解扫描 -->
<context:component-scan base-package="com.ityang"></context:component-scan>
<!-- 开启事务注解的支持
transaction-manager:写事务管理器的id
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
- 在业务层加@Transactional注解;在find开头的方法加只读事务
@Transactional注解也可以加在方法上,如果类上和方法上都有@Transactional,则以方法上的为准
@Service("accountService")
@Transactional//该类中所有的方法都加可读写的事务
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
@Override
public void transfer(Long fromId, Long toId, Double money) {
Account fromAccount = accountDao.findById(fromId);
Account toAccount = accountDao.findById(toId);
fromAccount.setMoney(fromAccount.getMoney() - money);
toAccount.setMoney(toAccount.getMoney() + money);
accountDao.update(fromAccount);
int i = 10 / 0;
accountDao.update(toAccount);
}
@Override
@Transactional(readOnly=true) // 只读事务
public void findById(Long id) {
Account fromAccount = accountDao.findById(id);
fromAccount.setMoney(10000D);
accountDao.update(fromAccount);
}
}
- 测试(测试代码跟xml一样)
实际开发中,事务我们用xml配置,因为可以一劳永逸