小编典典

spring悲观锁定

hibernate

我在java下有spring项目,使用hibernate查询,我喜欢使用悲观锁定。

在Spring + Hibernate中如何进行悲观锁定?

编辑:

@Loggable(value = LogLevel.TRACE)
@Transactional
@Override
public void updateBalance(String id, BigDecimal amount) {
    Session session = sessionFactory.getCurrentSession();
    sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.flush();
    Account acc = (Account) session.get(Account.class, id, LockMode.UPGRADE);
    acc.setName("New Account");
    acc.setBalance(acc.getBalance().subtract(amount));
    save(acc);
    try{
        tx.commit();
    }catch (TransactionException e){
        tx.rollback();
    }
    session.close();
}

问题:

我想在一个方法中使用悲观锁定,并且我将此方法称为从不同的方法。当我从第一个方法调用它时,悲观的工作效果很好,但是当我从第二个方法调用它时,它给出了(无法提交事务)

例外:

Could not commit Hibernate transaction; nested exception is org.hibernate.
TransactionException: Transaction not successfully started

阅读 221

收藏
2020-06-20

共1个答案

小编典典

http://www.amicabile.com/hybernate/hybernate-
chapter5.html

http://javacompleteexamples.blogspot.com/2009/07/how-db-locking-system-works-
in.html

编辑:

尝试:

@Override
@Loggable(value = LogLevel.TRACE)
@Transactional
public void updateBalance(String id, BigDecimal amount) {
        Account acc = (Account) sessionFactory.getCurrentSession().get(Account.class, id, LockMode.UPGRADE);
        acc.setBalance(acc.getBalance().subtract(amount));
        save(acc);
}
2020-06-20