23

I have one question about optimistic locking in Hibernate. I am trying to go deep inside optimistic locking with Hibernate, but I have one doubt. Hibernate uses version approach (integer or timestamp) to implement optimistic locking. To configure you can use @Version annotation (or xml configuration) and create a version attribute. The other option is configuring without versioning using optimistic-lock="all" attribute.

My question is in case that you don not define any versioning attribute and also you do not specify an optimistic-lock attribute, which strategy uses Hibernate in this cases? Pessimistc Locking I am pretty sure that no, so I suppose that is optimistic locking but don't know how.

Thank you very much for your attention.

2 Answers 2

57

If you don't configure Hibernate to use optimistic locking, it uses no locking at all. So, in this case last update always wins.

Just to make it clear, note that Hibernate optimistic locking is completely different from DBMS transaction isolation. Hibernate optimistic locking only works in situation when you load object in one transaction, modify it and save it later in another transaction. In this case optimistic locking ensures that some other transaction haven't changed that object in the database in between. However, optimistic locking doesn't affect isolation of concurrent transactions - so, locks (optimistic or pessimistic) used by DBMS internally to implement transaction isolation still works, no matter whether Hibernate locking is enabled or not.

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

Comments

4

@axtavt, you right, but question about how hibernate implement optimistic locking without @Version column.

Today four OptimisticLockType options available:

/**
 * Perform no optimistic locking.
 */
NONE,
/**
 * Perform optimistic locking using a dedicated version column.
 *
 * @see javax.persistence.Version
 */
VERSION,
/**
 * Perform optimistic locking based on *dirty* fields as part of an expanded WHERE clause restriction for the
 * UPDATE/DELETE SQL statement.
 */
DIRTY,
/**
 * Perform optimistic locking based on *all* fields as part of an expanded WHERE clause restriction for the
 * UPDATE/DELETE SQL statement.
 */
ALL

I think this is enough to answer the original question.

3 Comments

Could you elaborate about each option ?
I feel like Javadoc pretty self-explanatory. Do you have question on some particular option?
I've read user guide and now I understand it. If someone interested in please follow docs.jboss.org/hibernate/orm/6.0/userguide/html_single/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.