How to recover after Hibernate’s OptimisticLockException

I've read many articles about optimistic locking and OptimisticLockException itself. Problem is that each one of them ended up getting their first exception and no word on recovery. What to do next? Repeat? If so, how? Or drop it? Is there any chance to continue? How? Even more, documentation says that if you get Hibernate exception - you're done, it's not recoverable:

An exception thrown by Hibernate means you have to rollback your database transaction and close the Session immediately (this is discussed in more detail later in the chapter). If your Session is bound to the application, you have to stop the application. Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction. This means that the database state and the business objects will be out of sync. Usually this is not a problem, because exceptions are not recoverable and you will have to start over after rollback anyway.

Here is my attempt on this: repeatable and recoverable.

Business case

Let's say we have distributed application with two web servers, connected to the same database. Applications use optimistic locking to avoid collisions. Customers buy lottery coupons, which are numbered from 1 to 100. In the same second Alice on web server 1 draws two coupons: 11 and 12. In the same moment Bob reserves two coupons on web server 2. It draws 11 and 13 for Bob and tries to write it back to database. But it fails, since Alice's commit was first. I want a web application server to draw coupons for Bob again and then - try to save again until it succeeds.


For every request Hibernate associates different Session that is flushed at the end of request processing. If you hit OptimisticLockException then this Request Session is polluted and will be rolled back. To avoid this we will create a separate Hibernate's Session especially for drawing coupons. If separate session fails - drop this session and try again in a new one. If it succeeds - merge it with a main request session. Request Session cannot be touched during draws. Take a look at the following picture:

On this picture yellow and green short-term sessions has failed with OptimisticLockException. Red session was successful and these objects are merged to a main session on the left.

Reservation entity

Key requirement here is to keep a domain you want to lock on as small as possible and not coupled directly to anything else. Best approach here is to create some Reservation entity with few fields, let's say: couponId and customerId. For each Coupon create one Reservation row and use reserved boolean field as a reservation status. For coupon and customer use weak identifiers (long) instead of real entities. This way no object tree will be loaded and Reservation stays decoupled.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

import static org.apache.commons.lang3.Validate.isTrue;
import static org.springframework.util.Assert.isNull;

public class Reservation {
private long id;
private long couponId;
private Long customerId;
private boolean reserved;

public void reserve(long reservingCustomerId) {
isTrue(reserved == false);
reserved = true;
customerId = reservingCustomerId;

Method reserve has some business assertions to keep it legit. You can also spot lombok's annotations that provide getters, setters and toString methods on the fly.

Reservation Service

Reservation Service implements my solution. I've commented some steps for better reading. Please read a source code:

import lombok.extern.slf4j.Slf4j;
import org.hibernate.*;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;

import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceContext;
import java.util.List;

public class ReservationService {

private HibernateEntityManager hibernateEntityManager;

private Iterable<Reservation> reserveOptimistic(long customerId, final int count) throws NoFreeReservationsException {"Trying to reserve {} reservations for customer {}", count, customerId);

//This is the request session that needs to stay clean
Session currentSession = hibernateEntityManager.getSession();
Iterable<Reservation> reserved = null;

do {
//This is our temporary session to work on
Session newSession = hibernateEntityManager.getSession().getSessionFactory().openSession();
Transaction transaction = newSession.beginTransaction();

List<Reservation> availableReservations = null;

try {
Query query = newSession.createQuery("from Reservation r where r.reserved = false")
.setLockMode("optimistic", LockMode.OPTIMISTIC)

availableReservations = query.list();

//There is no available reservations to reserve
if (availableReservations.isEmpty()) {
throw new NoFreeReservationsException();

for (Reservation available : availableReservations) {

//Commit can throw optimistic lock exception if it fails

//Commit succeeded - this reference is used outside try-catch-finally block
reserved = availableReservations;

} catch (OptimisticLockException | StaleObjectStateException | HibernateOptimisticLockingFailureException e) {"Optimistic lock exception occurred for customer {} and count {}: {} {}", customerId, count, e.getClass(), e.getMessage());


for (Reservation availableMsisdn : availableReservations) {
} finally {
//Repeat until we reserve something
} while (reserved == null);"Successfully reserved {} reservations for customer {}", count, customerId);

//Merge reserved entities to request session
for (Reservation reservedMsisdn : reserved) {

return reserved;

This code says it all. It tries to reserve some Reservations until it succeeds in a do-while loop. Main Request Session is not polluted and it achieves our goal.

I hope this example helps you in similar some cases. It works as expected for a few months on our customer's production site and I recommend this solution.

Unable to instantiate default tuplizer

I wrote few hbm mappings for domain classes in my recent project, and I got exception like that:
org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
Of course my first thought was googling for it and I found interesting answers. Most commons causes of this exception are:
  • missing getters or setters, what's more, even a typo or wrong letter case (like getParentproject instead of getParentProject when field in class and mapping file is defined as parentProject)
  • missing default constructor
  • missing dependency for javassist library
My files seemed to be correctly defined, so it had to be missing dependency.
To fix it I've added these lines to my pom.xml:
Well, it shouldn't be a surprise because in full stacktrafe from this error there is an entry:
java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
What explicitly indicates where is the root of this problem ;) (And BTW: in my recent project I'm stuck with quite old version of Hibernate - 3.6.3)

Hibernate Envers with Grails 2.1.0

Our client requires that every entity in his Grails application has to be audited with detailed information: who and when did exactly what? It is a perfect opportunity to use Hibernate Envers! It turned out not as straightforward as I thought, so I want to share my experience with you.


I use latest release of Grails with version 2.1.0. I've created a sample application on github for you as an example - SpOOnman/enversdemo. All files and techniques mentioned here can be found inside it. If you have other experiences with Grails and Envers working together, please share in comments.

Grails Envers plugin

First I've searched for a Grails plugin. I've found one outdated on google code and a (more modern) on github. This plugin is created by Lucas Ward and it has great introductionary blog post by author. This is a great place to start.

Unfortunately Lucas Ward's plugin supports Grails up 1.3.7 and it comes with outdated Envers version. I've searched through forks and I've found most up-to-date fork by Matija Folnovic: It supports Grails 2.1 out of the box. Edit: Matija pointed out that credit should go to Jay Hogan and Damir Murat for their work on upgrading Envers plugin to Grails 2.

Matija's plugin is not packaged nor published so you have to package it by yourself:

Copy (and rename to to your application's lib diretory or publish to your company maven repository if you have one. Last step is to include a plugin in your BuildConfig.groovy:

Audit with Envers!

It's really easy to audit all entities with Envers. All you have to do is to use @Audit annotation on entities. SpOOnman/enversdemo audits Hotels and Bookings:

Envers plugin comes with some handy methods. For example Hotel.findAllRevisions() returns list of previous revisions. Once again I recommend a great blog post by Lucas Ward with many examples.

Grails and transactions

Grails has some glitches working with Envers. Envers is closely tied to database transactions. This means that it runs its listeners at the transaction end, when session is flushed. This is not always the case in Grails and it's the cause of some problems. You need to make some small modifications to your application to be sure that Envers works fine.

  • controllers - you need to annotate your controllers (or separate controller methods) with @Transactional and for every save you need to flush a session manually, e.g. save(flush: true). Otherwise Envers may not be notified.
  • services in Grails are transactional by default. However you mey explicitily set them with static transactional = true to be sure that this is not altered. I recommend to use session flushing on every save as well.
  • BootStrap.groovy script is not transactional. If you want Envers to audit your changes in this script you need to wrap your inserts with transactions. You can achieve it by using withTransaction closure. You need session flushing too. Take a look at SpOOnman/enversdemo BootStrap.groovy for an example.
  • integration tests wrap every test in a separate transaction that is rolled back at the end of a test, hence Envers won't work here. You need to disable wrapped transactions with static transactional = false. Remember that your changes are commited to database. To fulfill a contract of an empty database for every test you need to take care of cleaning up a database manually. Here is my sample integration test.

Add User to revision entities

By default Envers comes with a DefaultRevisionEntity class and creates its instance for every change on audited instance. It keeps information about entity revision, date and modification type. It lacks information about a user that made a change. I want to extend it.

There is already a code inside a plugin (here and here) but it's not packaged with a plugin itself. I guess it's because it adds dependency to Spring Security. This not a problem for me since I already use Spring Security plugin already in my application. I decided to add missing classes inside my application.

First I need a domain class - UserRevisionEntity. New instance of this class is created for every revision saved by Envers. It is a simple domain class with some extra annotations:

Notice that I've made currentUser field nullable. There may be some actions that doesn't require user to be logged in. Also, there is no user while executing BootStrap.groovy script.

Annotations @RevisionNumber and @RevisionTimestamp are required by Envers as described in documentation. @RevisionEntity annotation configures Envers to use non-default listener - SpringSecurityRevisionListener. It looks simple:

SpringSecurityRevisionListener's newRevision method fills each UserRevisionEntity instances with currently logged User.


Envers offers some configuration options listed on documentation page. Options can be set in persistence.xml. However in Grails there is no persistence.xml. You can add it (and Grails supports it), but I've found other way to configure properties. I use System.setProperties to configure Envers and I place it in grails-app/conf/spring/resources.groovy. This is an example to change Envers tables' prefix and suffix:


Testing Envers makes sense only with Grails integration tests. As I've mentioned earlier you must disable transactions that wrap your tests in order for Envers listeners to work. Also make sure you use withTransaction, session flushing and you've marked your controllers as @Transactional. There rules all stand in integration tests too. Example integration test can look like this:


Hibernate Envers does a great job auditing my application. It is easy to use, despite all the small glitches I've mentioned here. Special thanks to plugin authors that package Envers library in a plugin that can be used out of the box. I really recommend it! It would be great to hear all your thoughts on Envers and Grails working together so I can improve this post for others too.

Update 12.04.2013

Lucas Ward has posted updaate entry on Grails Hibernate Envers plugin here: Thanks!