V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
PhilFreecess
V2EX  ›  问与答

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

  •  
  •   PhilFreecess · Dec 31, 2020 · 487 views
    This topic created in 1944 days ago, the information mentioned may be changed or developed.
         /**
         * 开启事务
         */
        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

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6166 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 02:16 · PVG 10:16 · LAX 19:16 · JFK 22:16
    ♥ Do have faith in what you're doing.