我在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();
}
问题:
我想在一个方法中使用悲观锁定,我从不同的方法调用这个方法。当我从第一种方法调用它时悲观工作正常,但是当我从第二种方法调用它时它给出(事务无法提交)
异常(exception):
Could not commit Hibernate transaction; nested exception is org.hibernate.
TransactionException: Transaction not successfully started
最佳答案
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);
}