明确
第一:
JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。
第二:
spring框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在spring-tx-4.2.4.RELEASE.jar中。
第三:
spring的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。
API介绍
PlatformTransactionManager
TransactionDefinition
事务的隔离级别
脏读:一个事务读到了另一个事务没有提交的数据
不可重复读:一个事务读到了另一个事务已经提交的update数据
虚读:一个事务读到另一个事务的insert数据
一个是前后数据不一样,一个是前后条数不一样
事务的传播行为
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
是否是只读事务
建议查询时设置为只读。
TransactionStatus
环境搭建
AccountServiceImpl.java
package com.itheima.service.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
/**
* 账户的业务层实现类
* @author zhy
*
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户信息
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
//3.更新账户信息
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
AccountDaoImpl.java
package com.itheima.dao.impl;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
/**
* 账户的业务层实现类
* @author zhy
*
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer accountId) {
List<Account> list = getJdbcTemplate().query("select * from account where id = ? ", new BeanPropertyRowMapper<Account>(Account.class),accountId);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = getJdbcTemplate().query("select * from account where name = ? ", new BeanPropertyRowMapper<Account>(Account.class),name);
if(list.isEmpty()){
return null;//没有这个名称的账户
}
if(list.size()>1){
//结果集不唯一,不符合我们的约定
throw new RuntimeException("结果集不唯一,请检查数据");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
Client.java
package com.itheima.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
/**
* 测试类
* @author zhy
*
*/
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService accountService = (IAccountService) ac.getBean("accountService");
// Account account = accountService.findAccountById(1);
// System.out.println(account);
accountService.transfer("aaa", "bbb", 100f);
}
}
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: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/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">
<!-- 配置service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置SPRING内置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/day66_spring_jabctemplate"></property>
<property name="username" value="root"></property>
<property name="password" value="suntong"></property>
</bean>
</beans>
Client.java
package com.itheima.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
/**
* 测试类
* @author zhy
*
*/
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService accountService = (IAccountService) ac.getBean("accountService");
// Account account = accountService.findAccountById(1);
// System.out.println(account);
accountService.transfer("aaa", "bbb", 100f);
}
}
此时扣钱的扣了,但是收钱的没加
基于xml的声明式事务配置
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: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/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">
<!-- 配置service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置SPRING内置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/day66_spring_jabctemplate"></property>
<property name="username" value="root"></property>
<property name="password" value="suntong"></property>
</bean>
<!-- spring基于XML的声明式事务控制 -->
<!-- 第一步:配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 第二步:配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 第四步:配置事务的属性
isolation:配置事务的隔离级别。默认值:DEFAULT,使用数据库的默认隔离级别。mysql是REPEATABLE_READ
propagation:配置事务的传播行为。默认值是:REQUIRED。 一般的选择。(增删改方法)。当是查询方法时,选择SUPPORTS
timeout:指定事务的超时时间。默认值是:-1,永不超时。当指定其他值时,以秒为单位
read-only:配置是否只读事务。默认值是:false,读写型事务。 当指定为true时,表示只读,只能用于查询方法。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常时,事务不回滚。没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当执行产生该异常时,事务不回滚。产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 第三步:配置aop
要配的是:切入点表达式
通知和切入点表达式的关联
-->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<!-- 配置事务通知和切入点表达式的关联 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
此时事务可以回滚,钱可以正常转入转出
xml加注解
AccountDaoImpl.java
package com.itheima.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
/**
* 账户的业务层实现类
* @author zhy
*
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccountById(Integer accountId) {
List<Account> list = jdbcTemplate.query("select * from account where id = ? ", new BeanPropertyRowMapper<Account>(Account.class),accountId);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = jdbcTemplate.query("select * from account where name = ? ", new BeanPropertyRowMapper<Account>(Account.class),name);
if(list.isEmpty()){
return null;//没有这个名称的账户
}
if(list.size()>1){
//结果集不唯一,不符合我们的约定
throw new RuntimeException("结果集不唯一,请检查数据");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
AccountServiceImpl.java
package com.itheima.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
/**
* 账户的业务层实现类
* @author zhy
*
*/
@Service("accountService")
//@Transactional(propagation=Propagation.REQUIRED,readOnly=false)//读写型
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)//只读型
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户信息
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
//3.更新账户信息
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!-- 配置jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置SPRING内置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/day66_ee287_spring"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- spring基于XML和注解组合的配置步骤-->
<!-- 第一步:配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 第二步:配置spring开启注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 在需要事务的地方使用@Transactional注解
该注解可以写在接口上,类上和方法上。
写在接口上,表示该接口的所有实现类都有事务。
写在类上,表示该类中所有方法都有事务。
写在方法,表示该方法有事务。
优先级:就近原则。
-->
</beans>
纯注解方式
AccountServiceImpl.java
package com.itheima.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
/**
* 账户的业务层实现类
* @author zhy
*
*/
@Service("accountService")
@Transactional(propagation=Propagation.REQUIRED,readOnly=false)//读写型
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)//只读型
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//1.根据名称查询账户信息
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targetName);
//2.转出账户减钱,转入账户加钱
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
//3.更新账户信息
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
Client.java
package com.itheima.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
/**
* 测试类
* @author zhy
*
*/
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService accountService = (IAccountService) ac.getBean("accountService");
// Account account = accountService.findAccountById(1);
// System.out.println(account);
accountService.transfer("aaa", "bbb", 100f);
}
}
jdbcConfig.java
package config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* 连接数据库的配置类
* @author zhy
*
*/
public class JdbcConfig {
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
@Bean(name="dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/day66_spring_jabctemplate");
ds.setUsername("root");
ds.setPassword("suntong");
return ds;
}
}
SpringConfiguration.java
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* spring的配置类,作用就是当bean.xml用
* @author zhy
*
*/
@Configuration
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionManager.class})
@EnableTransactionManagement
public class SpringConfiguration {
}
TransactionManager.java
package config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
/**
* 事务控制的配置类
* @author zhy
*
*/
public class TransactionManager {
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}