======== 模拟转账 ======== 在针对t_account表的数据访问接口中添加方法: // 针对t_account表的数据访问接口 public interface IAccountDao { ... // 支出 public int outAccount(int accountId, double money); // 收入 public int inAccount(int accountId, double money); ... } 在针对t_account表的数据访问接口实现中添加方法: // 针对t_account表的数据访问接口实现 @Repository public class AccountDao implements IAccountDao { @Resource // 注入JDBC模板 private JdbcTemplate jdbcTemplate; ... // 支出 public int outAccount(int accountId, double money) { // 定义SQL语句 String sql = "update t_account set money = money - ? " + "where account_id = ?"; // 设置参数 Object[] args = {money, accountId}; // 执行SQL语句 int nrows = jdbcTemplate.update(sql, args); // 返回受影响的行数 return nrows; } // 收入 public int inAccount(int accountId, double money) { // 定义SQL语句 String sql = "update t_account set money = money + ? " + "where account_id = ?"; // 设置参数 Object[] args = {money, accountId}; // 执行SQL语句 int nrows = jdbcTemplate.update(sql, args); // 返回受影响的行数 return nrows; } ... } 在cn.tedu.springjdbc.service包下创建账户服务类: // 账户服务类 @Service public class AccountService { @Resource // 注入数据访问对象 private IAccountDao accountDao; ... // 转账 public boolean transferAccounts(int outId, int inId, double money) { boolean success = false; // 返回值 // 源账户支出 int outRows = accountDao.outAccount(outId, money); // 目的账户收入 int inRows = accountDao.inAccount(inId, money); // 如果支持和收入都成功则转账成功 if (outRows == 1 && inRows == 1) success = true; return success; } ... } 编写测试用例: // 账户服务测试类 public class SpringJDBCTestAccountService extends SpringJDBCTest { @Resource // 注入账户服务对象 private AccountService accontService; ... // 测试:转账 @Test public void testTransferAccounts() { // 转账 boolean success = accontService.transferAccounts(1, 2, 100); System.out.println(getClass().getName() + "." + Thread .currentThread().getStackTrace()[1].getMethodName() + ": " + success); } ... } 运行测试用例: cn.tedu.springjdbc.test.SpringJDBCTestAccountService.testTransferAccounts: true 看库。 假设在支出操作和收入操作之间发生故障: // 转账 public boolean transferAccounts(int outId, int inId, double money) { boolean success = false; // 返回值 // 源账户支出 int outRows = accountDao.outAccount(outId, money); int i = 1 / 0; // 故障 // 目的账户收入 int inRows = accountDao.inAccount(inId, money); // 如果支持和收入都成功则转账成功 if (outRows == 1 && inRows == 1) success = true; return success; } 发现源账户被扣款,但目的账户的余额并没有增加。 理想的情况应该是,如果目的账户没有收入,源账户也不应该有支出。 这就是事务要解决的问题!