Optimistic Locking Versioning in JPA (Annotations)

This tutorial explains Optimistic Locking, simulates the problem and then solves the problem using Optimistic Locking Versioning in Hibernate using JPA Annotations.

1. Definition

The standard Definition for Optimistic Locking is

“Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check reveals conflicting modifications, the committing transaction rolls back.”

Lets us consider a simple sequence of events to explain the above definition.

2. Scenario

Scenario: Lets say there are two people John & Tom who want to book a ticket for an Event and there is only one ticket left.

1. John logs in and selects the only available ticket say Ticket 10 and hasn’t booked it yet.

2. Tom logs in and selects the same Ticket 10 and quickly books it and gets a confirmation.

3. John also now clicks on Book and he too is confirmed the same ticket.

The above scenario can be avoided using Optimistic Locking.

3. Simulation

Lets simulate the above in our Code.

a. Project Setup

Lets create a simple Maven project with the below pom.xml

In the above pom.xml we added dependencies for Hibernate 3.6.10, MySQL Connector 5.1.25, javassist and sl4j for logging.

b. Database Table Creation

c. JPA Entity Class

Lets us create a JPA Entity  Class Ticket.java

d. Main Program

e. Output

Output

Output

From the above Console Output we could see that both the Update Statements were executed successfully. (Both John & Tom booked the same Ticket successfully.)

4. Fix

In order to fix the above issue lets add a new column to the TICKET table using the below ALTER statement.

After executing the above statement TICKET Table now is like.

TICKET

TICKET

We shall also modify out Ticket.java appropriately by adding a new field with getters and setters.

In the above getter the annotation @Version does the trick.

On running the Main Program JPAMain.java described above, we get the below Console Output.

Output

Output

5. Project Structure

Project Structure

Project Structure

Download Optimistic Lock & Versioning in JPA Example

Note: The above described TICKET table is designed in that way just for understanding the concept in a simple way, a RealWorld Ticket Booking Database Table wont be designed so. Also the variable naming conventions used for EntityManager,Ticket and Transaction are  named for better/easier understanding.

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *