Domanda

I've read about @Version annotation in Hibernate. Seems I've got a shallow understanding of it, or to be more precise - bad understanding of where it's needed.

Situation: Suppose I have Repeatable Read isolation level. And I have two pieces of code executed simultaneously:

code1:

sessionFactory.openSession();
MyEntity entity = (MyEntity) session.get(MyEntity, 10);
entity.setValue(5);
session.getTransaction().commit();

code2:

sessionFactory.openSession();
MyEntity entity = (MyEntity) session.get(MyEntity, 10);
entity.setValue(10);
session.getTransaction().commit();

Questions:

  • What will be result WITHOUT @Version annotation in MyEntity class?
  • What will be result WITH @Version annotation in MyEntity class?
  • *[Main]*If result is the same, than what the advantage of using @Version annotation?
È stato utile?

Soluzione

First if you have repeatable read isolation level ,Your second transaction will be executed only after the first commits.So there is no use in optimistic locking. When you use optimistic locking ,db will note down the version when it reads an entity and while it writes the updated entity back it will check if the version is modified.If modified it will throw an OptimisticLockException else it will write the updated entity and update the version

Altri suggerimenti

So if you add a @Version your table will have beside regular columns a column called version.

To that is incremented each time a new value is commited.

in code 1 you have session.get your entity will have a version 'x'

when code 2 read you might have as well version 'x' so if code 1 commits you will have version x+1 and by the time code2 commits will see difference in version throwing an exception.

Without you will just override the value code 1 wrote into DB.

If you do not use a locking strategy, the last commit would 'win'. Some providers implement optimistic locking per default, so you do not have to set any properties on the session or the query.

If you do use an optimistic locking strategy, the first transaction would increment the version and the second transaction would get an OptimisticLockException.

You can then catch it, refresh the entity and, perhaps, retry your changes.

The difference between using a version field and not using one is that not all locking strategies are required to be implemented for entities without a version field. Thus defining a @Version field makes your code more portable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top