4

我有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
4

1 回答 1

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);
}
于 2011-08-02T15:09:30.077 回答