Wednesday, April 25, 2018

Locking in JPA


PESSIMISTIC_WRITE

Locking is used for protecting mutable shared data. An PESSIMISTIC_WRITE lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or a PESSIMISTIC_WRITE lock.


String strSql = "Select person FROM Person person WHERE person.id =:id" +
"AND person.historyNo = (Select Max(person2.historyNo)from Person person2
WHERE person2.id =:id)"; 

TypedQuery<Person> query = entityManager.createQuery(strSql, Person.class);

query.setParameter("id", p.id);
query.setLockMode(LockModeType.PESSIMISTIC_WRITE); query.setHint("javax.persistence.lock.timeout", 0);

Long historyNo = new Long(0); historyNo = query.getSingleResult().getHistoryNo(); p.setHistoryNo(historyNo + 1);

entityManager.persist(p);

No comments:

Post a Comment

Create a REST API with Spring Boot

In this post, I will explain how to create a simple a REST API with Spring Boot Spring Boot Spring Boot is a framework that provides inbuil...