What is optimistic locking field of JPA

2

What is and what is JPA's Optimistic Locking Field? I noticed that this option exists for Eclipse Link and for Hibernate and this function is enabled when annotating a version attribute within an entity class, but I do not understand what its purpose is, when to use it and what its advantages. >

Example class 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 Link Documentation citing this option

    
asked by anonymous 21.03.2017 / 14:44

1 answer

1

The purpose of Lock is to prevent inconsistencies from occurring due to concurrent access to a resource. There are basically two locking strategies: the optimist and the pessimist. The pessimist simply blocks access to the resource until it is available again. The optimist allows the access but verifies if the item was modified after its loading. How to do this? Through the version attribute. The version lets you know if there is 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 go persist it I see that it has changed to version 2 I know someone moved then the exception can be thrown warning of the inconsistency of the registry . So you do not run the risk of someone overwriting information saved by someone else.

    
21.03.2017 / 15:05