0

Env:

Java EE 7 JPA 2.1 EJB 3.1 Hibernate 4 

Recently we are experiencing data problems in one of the table. Couple of points

  1. The table is mapped to JPA entity
  2. Table as well as Entity does not have "version" column/attribute.

In other words, there is no optimistic locking available for this table. On doing RCA, it turned out to be concurrent data modification issues.

Questions :

  1. In such cases where @Version is not available/used (in other words optimistic locking), is using a singleton repository class is the only option to make sure data consistency is maintained ?

  2. What about pessimistic locking in such cases ?

  3. I believe its a general use case where an application (especially legacy) can have some tables with version column and some dont. Are there any known patterns for handling tables/entities without version column ?

Thanks in advance, Rakesh

1 Answer 1

1

JPA supports pessimistic locking and you are free to use it in case you cannot or do not want to use optimistic locking.

In short, EntityManager provides lock methods to lock already retrieved entity, and also overloaded em.find and em.merge, as well as Query.setLockMode provide means to supply lock options to apply locks atomically at the time when the data is retrieved from DB.

However, with pessimistic locking, you should be aware you should prevent deadlocks. The best way to tackle it is always locking at most one entity per transaction.

You might also consider setting timeout for attempt to lock an entity, so that your transaction does not wait for long time if the entity is already locked.

In more detail, a very intelligible explanation of optimistic and pessimistic locking with JPA is provided here, including differences between READ and WRITE lock modes and setting lock timeout.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.