0

I understand what is optimistic locking and "how it work" but I don't know how can I implement it on Java EE.

I have an entity in JPA and I add one more version column and I annotated it with @Version . But to have an optimistic locking management I need only @Version annotation?

This is my Java Class:

@Entity
public class MyClass implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
    //other variables
    @Version
    @Column(name = "version")
    private int version;
 //other code
}

In my project I use Stateless session bean to access to Entity class and persist more operations, so I use @TransactionManagement(TransactionManagementType.CONTAINER) by default to handle my transaction.

My doubt is: with @TransactionManagement(TransactionManagementType.CONTAINER) ( independently what is @TransactionAttribute (REQUIRED,MANDATORY etc)) and only annotating version variable in MyClass.java I obtain the optimistic locking management?

Antonio1996
  • 736
  • 2
  • 7
  • 22

1 Answers1

0

From Pro JPA 2: Mastering the Java™ Persistence API:

A couple of words of warning about version fields are in order. The first is that they are not guaranteed to be updated, either in the managed entities or the database, as part of a bulk update operation. (...) The second point worth remembering is that version fields will be automatically updated only when either the non-relationship fields or the owning foreign key relationship fields (e.g., many-to-one and one-to-one source foreign key relationships) are modified. (...) By default, JPA assumes (...) Read Committed isolation. Normal execution using version locking works with Read Committed isolation to provide additional data-consistency checks in the face of interleaved writes. Satisfying tighter locking constraints than what this locking offers requires that an additional locking strategy be used.

(emphasis mine)

So, to answer your question: No. Using @Version does not cover all the bases.

The aforementioned additional locking strategy involves passing an appropriate locking mode (OPTIMISTIC or OPTIMISTIC_FORCE_INCREMENT) to EntityManager.lock(), EntityManager.refresh(), EntityManager.find(), and Query.setLockMode(), where applicable. I won't go into more details here and instead recommend a follow up read (there's a detailed discussion in the book as well).

crizzis
  • 9,978
  • 2
  • 28
  • 47