What is Optimistic JPA Locking Field

Asked

Viewed 365 times

2

What is and what is the "Optimistic Locking Field" of JPA? I noticed that there is this option for Eclipse Link and Hibernate and this function is enabled when annotating a version attribute within an entity class, but I did not understand what its purpose, when I should use and what its advantages.

Class example annotated with @version

@Entity
public class Inventory {
    @Id
    @Column(name="ITEM_SKU", insertable=false, updatable=false)
    protected long id;

    @OneToOne
    @JoinColumn(name="ITEM_SKU")
    protected Item item;
    ...
    @Version
    protected int version;
    ...
    public void setItem(Item item) {
        this.item = item;
        this.id = item.getSKU();
    }
}

Eclipse Documentation Link quoting this option

  • 1

    This link can help you: http://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking

1 answer

1

The purpose of Lock is to prevent inconsistencies arising due to concurrent access to a resource. There are basically two lock strategies: The optimist and the pessimist. The pessimist simply blocks access to the resource until it is available again. The optimist allows access but checks if the item has been modified after loading. How to do this? Through the attribute version. The version allows you to know if there has been a change because it stores the currently loaded version of the object. So if I arrive and access the object that is in version 1 at the time of access, but then when I will persist it I see that it has changed to version 2 I know that someone moved so can be launched the exception warning of the inconsistency of the record. So there is no risk of someone overwriting information saved by another person.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.