一、spring中使用事务需要明确的
1、JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。
2、spring框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在spring-tx-4.2.4.RELEASE.jar中。
3、spring的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。
二、spring中事务控制的API
1、PlatformTransactionManager
此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:
而我们在开发中都是使用它的实现类,如下图:
注意:真正管理事务的对象
rg.springframework.jdbc.datasource.DataSourceTransactionManager 使用Spring JDBC或iBatis 进行持久化数据时使用
org.springframework.orm.hibernate3.HibernateTransactionManager 使用Hibernate版本进行持久化数据时使用
2、TransactionDefinition
它是事务的定义信息对象,里面有如下方法:
(1)、事务的隔离级别
(2)、事务的传播行为
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
(3)、超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
(4)、是否是只读事务
建议查询时设置为只读。
3、TransactionStatus
此接口提供的是事务具体的运行状态,方法介绍如下图:
三、基于XML的声明式事务控制
1、拷贝必要的jar包
2、创建spring配置文件,并导入约束
<?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">
</beans>
3、准备实体类和数据库
创建数据库
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
创建实体类
/**
* 账户的实体
* @author
*
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
4、编写service层
/**
* 账户的业务层接口
* @author
*
*/
public interface IAccountService {
/**
* 根据id查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);//查
/**
* 转账
* @param sourceName 转出账户名称
* @param targeName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targeName,Float money);//增删改
}
/**
* 账户的业务层实现类
* @author
*
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
5、编写dao层
/**
* 账户的持久层接口
* @author
*/
public interface IAccountDao {
/**
* 根据id查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
* @return
*/
Account findAccountByName(String name);
/**
* 更新账户信息
* @param account
*/
void updateAccount(Account account);
}
/**
* 账户的持久层实现类
* @author
* 此版本dao,只需要给它的父类注入一个数据源
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> list = getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),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 money = ? where id = ? ",account.getMoney(),account.getId());
}
}
/**
* 账户的封装类RowMapper的实现类
* @author
*/
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}
6、bean.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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">
<bean id="accountService" class="cn.itcast.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="cn.itcast.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知:
1、导入tx名称空间
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 配置事务的属性 -->
<tx:attributes>
<!-- 约定优于编码 -->
<!-- 事务的属性:
read-only:是否只读事务。建议查询使用只读事务。默认值false,不只读
isolation:事务的隔离级别。默认值是DEFAULT。使用数据库的默认隔离级别
propagation:事务的传播行为。默认值REQUIRED,总要有事务支持。
timeout:事务的超时时间。默认值是-1,永不超时。
rollback-for:指定的是一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
no-rollback-for:指定的是一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,表示任何异常都回滚。
-->
<tx:method name="*" propagation="REQUIRED" read-only="false" />
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- aop的配置 -->
<aop:config>
<aop:pointcut expression="execution(* cn.itcast.service.impl.*.*(..))" id="pt1"/>
<!-- 配置通知和切入点表达式的对应关系,当我们通知类型固定时,通知的方法增强哪些业务方法的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!-- 配置spring内置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 引入属性文件 -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
</beans>
四、基于注解的声明式事务控制
1、创建一个用于加载spring的配置类
package cn.itcast.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("cn.itcast")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class})
@EnableTransactionManagement//开启spring对注解事务的支持。
public class SpringConfiguration {
/*
* 开启对spring4.3之前版本对@PropertySource的支持
*
*/
@Bean
public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
package cn.itcast.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(@Qualifier("dataSource")DataSource ds){
return new JdbcTemplate(ds);
}
@Bean(name="dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(@Qualifier("dataSource")DataSource ds){
return new DataSourceTransactionManager(ds);
}
}
2、创建javaBean
package cn.itcast.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
3、创建业务层接口和实现类
package cn.itcast.service;
import cn.itcast.domain.Account;
/**
* 账户的业务层接口
* @author
*
*/
public interface IAccountService {
/**
* 根据id查询账户
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,Float money);
}
package cn.itcast.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 cn.itcast.dao.IAccountDao;
import cn.itcast.domain.Account;
import cn.itcast.service.IAccountService;
/**
* 账户的业务层实现类
* @author
*
*/
@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 id) {
return accountDao.findAccountById(id);
}
@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);
}
}
4、创建dao层接口和实现类
package cn.itcast.dao;
import cn.itcast.domain.Account;
/**
* 账户的持久层接口
* @author
*
*/
public interface IAccountDao {
/**
* 根据id查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
* @param name
* @return
*/
Account findAccountByName(String name);
/**
* 更新账户信息
* @param account
*/
void updateAccount(Account account);
}
package cn.itcast.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import cn.itcast.dao.IAccountDao;
import cn.itcast.dao.rowmapper.AccountRowMapper;
import cn.itcast.domain.Account;
/**
* 账户的持久层实现类
* @author
*
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account findAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
return accounts.isEmpty() ? null : accounts.get(0);
}
@Override
public Account findAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
//没有结果
if(accounts.isEmpty()){
return null;
}
//结果集大于1了,数据有问题
if(accounts.size() > 1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
}
}
package cn.itcast.dao.rowmapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import cn.itcast.domain.Account;
public class AccountRowMapper implements RowMapper<Account> {
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}
5、测试
package cn.itcast.ui;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.config.SpringConfiguration;
import cn.itcast.service.IAccountService;
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService accountService = (IAccountService) ac.getBean("accountService");
accountService.transfer("aaa", "bbb", 100f);
}
}