春天悲观锁定

时间:2011-07-29 10:58:35

标签: java database hibernate transactions pessimistic-locking

我在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();
}

问题:

我想在方法中使用悲观锁定,并且我从不同的方法中调用此方法。当我从第一种方法调用它时,悲观的工作正常,但是当我从第二种方法调用它时,它给出了(Transaction无法提交)

例外:

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

1 个答案:

答案 0 :(得分:3)

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);
}