八、转账案例(添加事务)
8.1 导入坐标,pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cpz</groupId>
<artifactId>spring_account</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
8.2 创建接口 AccountDao.java、AccountService.Dao
AccountDao.java
package com.cpz.dao;
import com.cpz.domain.Account;
public interface AccountDao {
public Account findByName(String name);
public void updateAccount(Account account);
}
AccountService.Dao
package com.cpz.service;
public interface AccountService {
public void transfer(String sourceName,String targetName,Float money);
}
8.3 账户的实体类
package com.cpz.domain;
public class Account {
private Integer id;
private String name;
private Float money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}
8.4 ConnectionUtils.java
作用:连接的工具类,它用于数据源中获取一个连接,并且实现和线程的绑定。
package com.cpz.utils;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionUtils {
// 让当前线程和Connection绑定
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
// 获取连接对象,并与本地线程绑定
public Connection getThreadConnection(){
// 获取线程中的Connection
Connection connection = tl.get();
// 线程第一次执行数据操作
if (connection == null){
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
// 线程绑定
tl.set(connection);
}
return connection;
}
// 如果线程结束,解绑
public void releaseConnection(){
tl.remove();
}
}
8.5 TransactionManager.java
作用:和事务管理相关的工具类,包含了开启、提交、回滚事务和释放连接。
package com.cpz.utils;
import java.sql.SQLException;
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
// 开启事务
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 提交事务
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 回滚事务
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 删除事务
public void close(){
try {
connectionUtils.getThreadConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
8.6 AccountDaoImpl.java
作用:注入连接工具对象,使得操作数据库从同一个连接中获取
package com.cpz.dao.impl;
import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import com.cpz.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class AccountDaoImpl implements AccountDao {
QueryRunner queryRunner;
ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
public Account findByName(String name) {
try {
List<Account> list = queryRunner.query(connectionUtils.getThreadConnection(),"select * from account where name = ?", new BeanListHandler<Account>(Account.class), name);
if (list == null || list.size() == 0){
return null;
}else if (list.size() > 1){
throw new RuntimeException("结果集不唯一,数据有问题!");
}
return list.get(0);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
queryRunner.update(connectionUtils.getThreadConnection(),"update account set money = ? where id = ?", account.getMoney(), account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
8.7 AccountServiceImpl.java
作用:注入事务管理器对象,对每个操作都需要开启事务、提交事务、关闭事务,如果抛出异常,需要回滚事务
package com.cpz.service.impl;
import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import com.cpz.service.AccountService;
import com.cpz.utils.TransactionManager;
public class AccountServiceImpl implements AccountService {
AccountDao accountDao;
TransactionManager transactionManager;
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void transfer(String sourceName, String targetName, Float money) {
try {
// 开启事务
transactionManager.beginTransaction();
// 执行操作
//1.根据名称查询转出账户
Account sourceAccount = accountDao.findByName(sourceName);
//2.根据名称查询转入账户
Account targetAccount = accountDao.findByName(targetName);
//3.转出账户减钱
sourceAccount.setMoney(sourceAccount.getMoney() - money);
// 设置异常
int i = 10 / 0;
//4.转入账户加钱
targetAccount.setMoney(targetAccount.getMoney() + money);
//5.更新转出账户
accountDao.updateAccount(sourceAccount);
//6.更新转入账户
accountDao.updateAccount(targetAccount);
// 提交事务
transactionManager.commit();
}catch (Exception e) {
e.printStackTrace();
// 回滚操作
transactionManager.rollback();
}finally {
// 释放连接
transactionManager.close();
}
}
}
8.8 ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="transactionManager" class="com.cpz.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<bean id="connectionUtils" class="com.cpz.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="accountService" class="com.cpz.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<bean id="accountDao" class="com.cpz.dao.impl.AccountDaoImpl">
<property name="queryRunner" ref="queryRunner"></property>
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<!--这里要去掉queryRunner的默认连接池配置,由ConnectionUtils 获取连接-->
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
8.9 测试类
package com.cpz.test;
import com.cpz.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringTest {
@Autowired
AccountService accountService;
@Test
public void transfer(){
accountService.transfer("aaa","bbb",100f);
}
}