我们先实现一个可以转张的项目:
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.qublog</groupId>
<artifactId>spring03_account</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</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.2.RELEASE</version>
</dependency>
</dependencies>
</project>
Account类:
package com.qublog.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 +
'}';
}
}
AccountDao接口:
package com.qublog.dao;
import com.qublog.domain.Account;
import java.util.List;
//账户的持久层接口
public interface AccountDao {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//根据名称查找账户,如果有唯一结果就返回,如果没有结果就返回null,如果结果集超过一个就抛异常
Account findAccountByName(String accountName);
}
AccountDaoImpl类:
package com.qublog.dao.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
//账户的持久层实现类
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try{
return runner.query("select * from account;",new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer id) {
try{
return runner.query("select * from account where id=?;",new BeanHandler<Account>(Account.class),id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try{
runner.update("insert into account(name,money) values(?,?);", account.getName(), account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try{
runner.update("update account set name=?,money=? where id=?;", account.getName(), account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer id) {
try{
runner.update("delete from account where id=?;",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query("select * from account where name = ?",new BeanListHandler<Account>(Account.class),accountName);
if (accounts == null || accounts.size() == 0) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,数据有问题");
}
return accounts.get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AccountService接口:
package com.qublog.service;
import com.qublog.domain.Account;
import java.util.List;
//账户的业务层接口
public interface AccountService {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//转账
void transfer(String sourceName, String targetName, Float money);
}
AccountServiceImpl类:
package com.qublog.service.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import java.util.List;
//账户的业务层实现类
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
public void transfer(String sourceName, String targetName, Float money) {
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新转出账户
accountDao.updateAccount(source);
//更新转入账户
accountDao.updateAccount(target);
}
}
AccountServiceTest类:
package com.qublog.test;
import com.qublog.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;
//使用Junit单元测试,测试我们的配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void testTransfer() {
as.transfer("aaa","bbb",100f);
}
}
执行结果为:
这时我们看数据发现没有任何问题,但当我们修改以下代码,如下:
AccountServiceImpl类:
public void transfer(String sourceName, String targetName, Float money) {
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//更新转入账户
accountDao.updateAccount(target);
}
这时执行测试,打印输出:
mysql中结果为:
可以看出明显错误。
下面我们分析代码:
AccountServiceImpl类:
public void transfer(String sourceName, String targetName, Float money) {
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//更新转入账户
accountDao.updateAccount(target);
}
代码中一共获取四个连接,前三个事务都成功了所以都提交了,但第四个事务前发生了除零异常,所以没有提交。
所以我们解决以上问题的思路就是:将transfer中的操作全放到一个连接中,所有操作要么全成功,要么全失败。
方法:使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个能控制事务的对象。
注意:事务的控制应该都是在业务层。
修改后的代码:
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.qublog</groupId>
<artifactId>spring03_account</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</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.2.RELEASE</version>
</dependency>
</dependencies>
</project>
Account类:
package com.qublog.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 +
'}';
}
}
AccountDao接口:
package com.qublog.dao;
import com.qublog.domain.Account;
import java.util.List;
//账户的持久层接口
public interface AccountDao {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//根据名称查找账户,如果有唯一结果就返回,如果没有结果就返回null,如果结果集超过一个就抛异常
Account findAccountByName(String accountName);
}
AccountDaoImpl类:
package com.qublog.dao.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import com.qublog.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
//账户的持久层实现类
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account;",new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer id) {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account where id=?;",new BeanHandler<Account>(Account.class),id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money) values(?,?);", account.getName(), account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?;", account.getName(), account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer id) {
try{
runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?;",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ?",new BeanListHandler<Account>(Account.class),accountName);
if (accounts == null || accounts.size() == 0) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,数据有问题");
}
return accounts.get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AccountService接口:
package com.qublog.service;
import com.qublog.domain.Account;
import java.util.List;
//账户的业务层接口
public interface AccountService {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//转账
void transfer(String sourceName, String targetName, Float money);
}
AccountServiceImpl类:
package com.qublog.service.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import com.qublog.utils.TransactionManager;
import java.util.List;
//账户的业务层实现类
//事务的控制应该都是在业务层的
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
try {
//开启事务
txManager.beginTransaction();
//执行操作
List<Account> accounts = accountDao.findAllAccount();
//提交事务
txManager.commit();
//返回结果
return accounts;
} catch (Exception e) {
//回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
//释放连接
txManager.release();
}
}
public Account findAccountById(Integer id) {
try {
//开启事务
txManager.beginTransaction();
//执行操作
Account account = accountDao.findAccountById(id);
//提交事务
txManager.commit();
//返回结果
return account;
} catch (Exception e) {
//回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
//释放连接
txManager.release();
}
}
public void saveAccount(Account account) {
try {
//开启事务
txManager.beginTransaction();
//执行操作
accountDao.saveAccount(account);
//提交事务
txManager.commit();
} catch (Exception e) {
//回滚操作
txManager.rollback();
} finally {
//释放连接
txManager.release();
}
}
public void updateAccount(Account account) {
try {
//开启事务
txManager.beginTransaction();
//执行操作
accountDao.updateAccount(account);
//提交事务
txManager.commit();
} catch (Exception e) {
//回滚操作
txManager.rollback();
} finally {
//释放连接
txManager.release();
}
}
public void deleteAccount(Integer id) {
try {
//开启事务
txManager.beginTransaction();
//执行操作
accountDao.deleteAccount(id);
//提交事务
txManager.commit();
} catch (Exception e) {
//回滚操作
txManager.rollback();
} finally {
//释放连接
txManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try {
//开启事务
txManager.beginTransaction();
//执行操作
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//更新转入账户
accountDao.updateAccount(target);
//提交事务
txManager.commit();
} catch (Exception e) {
//回滚操作
txManager.rollback();
e.printStackTrace();
} finally {
//释放连接
txManager.release();
}
}
}
ConnectionUtils类:
package com.qublog.utils;
import javax.sql.DataSource;
import java.sql.Connection;
//连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
//获取当前线程上的连接
public Connection getThreadConnection() {
try {
//先从ThreadLocal上获取
Connection conn = tl.get();
//判断当前线程上是否有连接
if (conn == null) {
//从数据源中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
tl.set(conn);
}
//返回当前线程上的连接
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//把连接和线程解绑
public void removeConnection() {
tl.remove();
}
}
TransactionManager类:
package com.qublog.utils;
//和事务管理相关的工具类,包含了,开启事务,提交事务,回滚事务,释放连接
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
//开启事务
public void beginTransaction() {
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
}
//提交事务
public void commit() {
try {
connectionUtils.getThreadConnection().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
//回滚事务
public void rollback() {
try {
connectionUtils.getThreadConnection().rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
//释放连接
public void release() {
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}
AccountServiceTest类:
package com.qublog.test;
import com.qublog.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;
//使用Junit单元测试,测试我们的配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void testTransfer() {
as.transfer("aaa","bbb",100f);
}
}
这时再次测试,打印结果:
进一步分析代码,我们发现配置变得非常麻烦,依赖注入乱七八糟,各个类之间互相依赖,