2
votes

I am new to use "optimistic locking" mechanism - I am using hibernate (in Jboss) and Container Managed Transaction (CMT). I want to handle the scenario when, between my entity-read and entity-update someone else updates the same entity (i.e. row) in DB. In such case I want to throw exception..

I have annotated my entity with @Version - like

@Version
private Long version;

Now, I am confused if this is enough for version management or I need to explicitly call the EntityManager.lock() api like

  {
    .
    .
    final QueryDTO queryDTO = entityManager.find(QueryDTO.class, id);
    entityManager.lock(queryDTO, LockModeType.READ);
    queryDTO.setStatus(updatedStatus);
    entityManager.persist(queryDTO);
  }

Thanks in advance,

1

1 Answers

7
votes

You don't need explicit locks (pessimistic locking) at all when using optimistic locking via @Version. When the entity is being updated to database, something like the following query will take place:

UPDATE QueryDTO SET status=<updated status>, ...other values..., version=100 WHERE id=<id> AND version=99

If the update fails (someone/something else has changed the data and version), you'll get OptimisticLockException (Since you're using EntityManager, I assume this is about JPA, in "raw" Hibernate it could have been something like StaleStateException).