【问题标题】:Spring + Hibernate - handling concurrency with @Transactional methodSpring + Hibernate - 使用@Transactional 方法处理并发
【发布时间】:2023-03-07 20:15:01
【问题描述】:

我遇到了多个线程同时访问某些事务方法的问题

要求是检查一个帐户是否已经存在或以其他方式创建它,下面代码的问题是如果两个线程并行执行具有相同帐户引用的 accountDao.findByAccountRef() 方法,如果他们没有找到该帐户,那么两者尝试创建相同的帐户,这将是一个问题, 谁能给我一些建议如何克服这种情况?

代码贴在下面

谢谢 拉梅什

@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) 
@Override
    public void createAccount(final String accountRef, final Money amount) {

        LOG.debug("creating account with reference {}", accountRef);

        if (isNotBlank(accountRef)) {
            // only create a new Account if it doesn't exist already for the given reference
            Optional<AccountEO> accountOptional = accountDao.findByAccountRef(accountRef);
            if (accountOptional.isPresent()) {
                throw new AccountException("Account already exists for the given reference %s", accountRef);
            }
            // no such account exists, so create one now
            accountDao.create(newAccount(accountRef, neverNull(amount)));
        } else {
            throw new AccountException("account reference cannot be empty");
        }
    }

【问题讨论】:

    标签: multithreading spring hibernate concurrency spring-transactions


    【解决方案1】:

    如果您希望系统在多人使用时也能正常运行,您可以使用乐观锁定的概念(我知道这里不涉及锁)。

    在创建时,通过尝试插入新帐户来工作,如果您因为主键重复而出现异常(您需要从异常中检查这一点),那么您知道该帐户已经创建.

    简而言之,您乐观地尝试创建行,如果失败,您知道那里已经有一个。

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 2014-06-18
      • 1970-01-01
      • 2019-03-30
      相关资源
      最近更新 更多