转账问题演示及解决(Aop的引出:ConnectionUtils(ThreadLocal)+TransactionManager)
转账问题分析事务
accountDao中的使用的是Jdbctemplate
由于更新中途出现异常,导致source的金钱扣了却没有转账到target账户上!!!
转账问题解决
该解决方法代码量冗余,配置文件逻辑复杂,仍有巨大优化空间(代理模式加强方法)
工具类部分(通过ThreadLocal绑定线程上的Connection)
ConnectionUtils(通过ThreadLocal绑定对象)
package com.czy.utils;
import javax.sql.DataSource;
import java.sql.Connection;
/**
* 连接工具类
* 它用于从数据源获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
private ThreadLocal tl = new ThreadLocal();
//用spring注入此对象
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection(){
//1.先从ThreadLocal上获取
Connection conn = tl.get();
try {
//2.判断当前线程上是否有连接
if (conn == null) {
//3.从数据源获取一个连接,并且和线程绑定(存入ThreadLocal中)
conn = dataSource.getConnection();
tl.set(conn);
}
}catch (Exception exception){
throw new RuntimeException(exception);
}
//4.返回当前线程上的连接
return conn;
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
TransactionManager(管理事务)
package com.czy.utils;
import java.sql.SQLException;
/**
* 事务管理相关的工具类,包含了开启事务,提交事务,回滚事务和释放连接
*/
public class TransactionManager {
//使用spring注入
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close(); //Connection还回连接池中
connectionUtils.removeConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
dao
package com.czy.dao.impl;
import com.czy.dao.AccountDao;
import com.czy.domain.Account;
import com.czy.utils.ConnectionUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate template;
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List findAllAccount() {
return template.query("select * from account",new BeanPropertyRowMapper(Account.class),connectionUtils.getThreadConnection());
}
public Account findAccountById(Integer id) {
return template.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper(Account.class),id,connectionUtils.getThreadConnection());
}
public void saveAccount(Account account) {
template.update("insert into account(name,money) values (?,?)",account.getName(),account.getMoney(),connectionUtils.getThreadConnection());
}
public void updateAccount(Account account) {
template.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId(),connectionUtils.getThreadConnection());
}
public void deleteAccount(Integer id) {
template.update("delete from account where id = ?",id);
}
public Account findAccountByName(String accountName) {
List accounts = template.query("select * from account where name = ?",new BeanPropertyRowMapper(Account.class),accountName,connectionUtils.getThreadConnection());
if(accounts == null || accounts.size() == 0)
return null;
else if(accounts.size() > 1)
throw new RuntimeException("结果集不唯一");
return accounts.get(0);
}
}
service
package com.czy.service.impl;
import com.czy.dao.AccountDao;
import com.czy.domain.Account;
import com.czy.service.AccountService;
import com.czy.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class AccountServiceImpl implements AccountService {
private AccountDao dao;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setDao(AccountDao dao) {
this.dao = dao;
}
public List findAllAccount() {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
List accounts = dao.findAllAccount();
//3.提交事务
txManager.commit();
//4.返回结果
return accounts;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
public Account findAccountById(Integer id) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
Account account = dao.findAccountById(id);
//3.提交事务
txManager.commit();
//4.返回结果
return account;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
public void saveAccount(Account account) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
dao.saveAccount(account);
//3.提交事务
txManager.commit();
//4.返回结果
}catch(Exception e){
//5.回滚操作
txManager.rollback();
}finally {
//6.释放资源
txManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
//根据名称查询转出账户
Account source = dao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = dao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户减钱
target.setMoney(target.getMoney()+money);
//更新两者
dao.updateAccount(source);
int i = 1/0;
dao.updateAccount(target);
//3.提交事务
txManager.commit();
//4.返回结果
}catch(Exception e){
//5.回滚操作
txManager.rollback();
e.printStackTrace();
}finally {
//6.释放资源
txManager.release();
}
}
}
配置文件(依赖注入)
<?xml version="1.0" encoding="UTF-8"?>
动态代理优化
package com.czy.factory;
import com.czy.domain.Account;
import com.czy.service.AccountService;
import com.czy.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
/**
* 用于创建Service的代理对象的工厂
*/
public class BeanFactory {
//通过spring获取
private AccountService accountService;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public AccountService getAccountService(){
final AccountService service = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
/**
* 添加事务的支持
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = null;
try{
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService,args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
}catch(Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
txManager.release();
}
}
});
return service;
}
}