Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

java - Spring Pessimistic locking

i have spring project under java, using hibernate query, i like to use pessimistic locking.

How to do Pessimistic locking in Spring + Hibernate?

Edit:

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

Problem:

i want to use pessimistic locking in a method, and i call this method from different to methods. pessimistic works fine when i call it from the first method, but it gives (Transaction couldn't be commit) when i call it from the second method

Exception:

Could not commit Hibernate transaction; nested exception is org.hibernate.
TransactionException: Transaction not successfully started
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Edit:

try:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...