V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
PhilFreecess
V2EX  ›  问与答

请问下老哥们,使用 Threadlocal 来管理事务,执行回滚后数据仍发生改变,该怎么解决?

  •  
  •   PhilFreecess · 2020-12-31 10:14:48 +08:00 · 234 次点击
    这是一个创建于 1225 天前的主题,其中的信息可能已经有所发展或是发生改变。
         /**
         * 开启事务
         */
        public void beginTransaction() {
            try {
                connectionUtils.getThreadConnection().setAutoCommit(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
    
    public void transfer(String sourceName, String targetName, Float money) {
    
            try {
                //开启事务
                transactionManager.beginTransaction();
    
                //执行操作
                //根据名称分别查询到转入转出的账户
                Account source = accountDao.findAccountByName(sourceName);
                Account target = accountDao.findAccountByName(targetName);
    
                //转入转出账户加减
                source.setBalance(source.getBalance() - money);
                target.setBalance(target.getBalance() + money);
    
                //更新转出转入账户
                accountDao.updateAccount(source);
                //模拟转账异常
                int num = 100 / 0;
                accountDao.updateAccount(target);
    
                //提交事务
                transactionManager.commit();
    
            } catch (Exception e) {
                //回滚操作
                transactionManager.rollback();
                e.printStackTrace();
            } finally {
                //释放连接
                transactionManager.release();
            }
        }
    

    跟着博客敲的代码,实现了转账的功能,抛出异常后调用了回滚方法,但是异常之前提交修改的数据仍然发生了改变,数据库引擎为 innodb,请问下怎么解决? https://i.imgur.com/tNorCDi.png https://i.imgur.com/NLeb1Wk.png https://i.imgur.com/7ia1Ntx.png

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3218 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:57 · PVG 21:57 · LAX 06:57 · JFK 09:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.