解决 Test.java 中事务
前期
基于 Spring_v6 xml 配置复制, 然后继续完成.
建项目, Maven 坐标, 仓库设置
Service 层添加方法
void transfer(String sourceName, String targetName, Float money);
ServiceImp 实现
@Override
public void transfer(String sourceName, String targetName, Float money) {
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney() - money);
//2.4转入账户加钱
target.setMoney(target.getMoney() + money);
//2.5更新转出账户
accountDao.updateAccount(source);
// int i=1/0;
//2.6更新转入账户
accountDao.updateAccount(target);
}
Dao 层添加添加方法
Account findAccountByName(String accountName);
daoImpl 实现
@Override
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);
}
}
test 层方法
@Test
public void testTransfer(){
as.transfer("赵薇","羽扬",1000f);
}
数据库信息
工具类 utils 实现
package com.yydcyy.utils;
/**
* @author YYDCYY
* @create 2019-09-26
* 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
package com.yydcyy.utils;
/**
* @author YYDCYY
* @create 2019-09-26
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
*/
public class TransactionManager {
test 执行 ok
service/AccountsServiceImpl 添加属性
private TransactionManager txManager;
及其 set().
bean.xml 取消注入数据源
DaoImpl 增加 connectionUtils 属性及其 setter()
daoImpl 所有方法使用 con…Utils.getThreadLocal()获取数据源
@Override
public List<Account> findAllAccount() {
try{
//return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}