UnitOfWork - java.lang.IllegalStateException: Existing session transaction state (false) does not match requested (true)

Viewed 86

After upgrading the dropwizard to 2.0.25, I am started getting this exception in the methods having @unitOfwork annotations ,

Can you help me out to rectify these errors ? why I am getting these errors now ?

Caused by: java.lang.IllegalStateException: Existing session transaction state (false) does not match requested (true)
at io.dropwizard.hibernate.UnitOfWorkAspect.validateSession(UnitOfWorkAspect.java:178)
at io.dropwizard.hibernate.UnitOfWorkAspect.beforeStart(UnitOfWorkAspect.java:85)
1 Answers

Short answer:
Add ManagedSessionContext.unbind(sessionFactory) to the end of your authenticator's authenticate method (right before/after closing the session).

Long answer:
After upgrading to Dropwizard 2.0.32, I was also having this exact problem - resource methods with @UnitOfWork annotations were throwing the exception you posted, with the same message. However, these methods also all had a parameter with the @Auth annotation, and I was able to determine that the problem only occurred when both annotations were present.

The authenticate method in my authenticator had the following structure.

Session session = sessionFactory.openSession();
ManagedSessionContext.bind(session);
// Do stuff using the session
session.close();

When I changed it to the following, the problem was resolved.

Session session = sessionFactory.openSession();
ManagedSessionContext.bind(session);
// Do stuff using the session
ManagedSessionContext.unbind(sessionFactory);
session.close();
Related