Hibernate provides two strategies of locking for performing secure read/write operations. Hibernate achieves this by database locking mechanism and abstains locking object in memory. So, basically hibernate locking depends on database for there operations. The two terms involved are as follows :

  • Optimistic

    This is used by hibernate to prevent from updating the record which is already modified in database. The approach says that there will be a column in table which explains the state of record called Version. It is usually a integer value which increments when the record is modified. By annotating the int type property of a persistence class with @Version will help hibernate to identify the version field.
    Hibernate simply compares the value of version field. If the updating record has version value less the the database record value, then it will throw an exception :

    org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
    

    Instead of int value, we can use Timestamp for same. Just define a property of Date type and annotate it with @Version. Now, the field will store the date & time when a new record is to create or modify the existing one, and also served the functionality of validating state of record.

  • Pessimistic

    The above approach did not provide the proper locking in terms of database. It was just to prevent database to update dirty records. In concurrently reading and updating data, it will always cause error because most of the time threads will pick the records which have been updated by another threads. In these type of cases, we need to lock the record so that no other transaction will access it until the current transaction gets complete. We use LockMode.UPGRADE to perform hibernate locking in parallel transaction mode.

You can get the sample code from here Hibernate Locking