[Hibernate] – How to work with locks ?


Problem :

Imagine the situation where in a store, you need to publish daily promotions and perform editing products. This store has several employees. What will happen if two or more of them update the information on a product at the same time? What data will be worth? What is saved first or last? As our application should handle this?


The data that will prevail will be the last informed. I call this : write conflict .


We can handle this scenario in some ways: A pessimistic approach would be to prevent the conflict from happening and ask for the database lock the record being updated.

The JPA supports Pessimistic Lock. The EntityManager has a lock method lock the record in the database. So only one person can access that record at the same time.


Product product = em.find(Product.class, 1);

Probably, it will not be the best solution. If another user attempts to perform this operation will have no access to information because it will be blocked.

Lock Optimistic

The idea is that the application / database never lock the access to the record, being optimistic, assuming that this is a situation not so frequent. But what do we do when there is a concurrent update? We have to prevent and treat the way that is most convenient according to the application business.

By @Version

public class Product {
    // ...
    private Integer version; 
    // ...

To save the version, you can use a numeric field or a timestamp (Calendar or Date). If the entity has @Version throughout update done, hibernate will automatically check the value of this field. If the record in the database has a lower value than is being sent to the version field, it accepts the update and increases its value. If you have a higher value, an exception of StaleObjectStateException type will be triggered within a javax.persistence.OptimisticLockException.

So, if two people try to update the same record, the first person will upgrade increasing its value. The last will be prevented from updating as attempts to sent a lower value than in the database.



1 Comment

  1. I’ve been surfing online greater than three hours as of late, but I never
    found any fascinating article like yours. It is pretty value enough for me.
    In my view, if all webmasters and bloggers made just right content
    material as you probably did, the net might be much
    more useful than ever before.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s