The pessimistic lock is the method of exclusively locking the target records when multiple transactions update the same record on the database. If a transaction sets a pessimistic lock for a particular record, another transaction cannot reference or update that record (however, in Oracle, the record can be referenced). A pessimistic lock is only available when JPQL is used.
If you use a pessimistic lock, until the transaction that obtained the lock terminates, the lock awaits release. Therefore, though the concurrent executions are not more than the optimistic lock, you can prevent the transaction commit errors that occur in the optimistic lock.
- How to specify a pessimistic lock
- Implement the pessimistic lock by using the query hint supported by Cosminexus JPA Provider. Execute the pessimistic lock by specifying the setHint() method of the Query method or by specifying @QueryHint in the @NamedQuery attribute.
- Example of implementing the pessimistic lock functionality
- An example of implementing the pessimistic lock functionality is as follows:
- Example of implementation 1
- An example of specifying the pessimistic lock in the setHint() method of the Query method is as follows:
Query query = manager.createQuery("SELECT emp FROM Employee AS emp");
query.setHint("cosminexus.jpa.pessimistic-lock","Lock"); |
- Example of implementation 2
- An example of specifying the pessimistic lock in @QueryHint of the @NamedQuery attribute is as follows:
@NamedQuery(
name="employee_list",
query="SELECT emp FROM Employee AS emp",
hints={ @QueryHint(name="cosminexus.jpa.pessimistic-lock", value="Lock") }
)
@Entity
public class Employee{
...
} |
- Note
- The pessimistic lock is only available for JPQL. The pessimistic lock is not enabled even by specifying the createNativeQuery method or by specifying @QueryHint in the hints attribute of @NamedNativeQuery. The pessimistic lock is also not enabled by specifying the hint attribute of the named-native-query tag in the O/R mapping file. Note that the locking specifications for the pessimistic lock in Cosminexus JPA Provider conform to the specifications of the database used.