Monday, July 27, 2009

Liferay messes up OpenSessionInView

It all started with the work I was doing on Liferay 5.2.3 a few months back. There is something wrong with Liferay/Hibernate/Spring Transaction integration. It just does not work. For one thing, Transaction demarcation either declaratively or through AOP relies on ThreadLocal or Thread based state. OpenSessionInView filter as implemented by Spring relies on or assumes that the thread that was dispatched for the request is the same one through out the request and response phases of the operation. By tying the SessionFactory and other state to the thread the filter is able to keep the session in view. I have not had the time to research this out more completely. It appears that Liferay uses different threads or atleast switches threads thus messing up the OSIV filter.

If you are trying to use Lazy Loading in Hibernate you are dependant on OSIV. With OSIV confused, you can say good bye to Lazy Loading, Transaction Demarcation and all the good stuff inside a Portlet.

The only way I could get Lazy Loading to work was by extracting some pieces of code from Spring's OpenSessionInViewInterceptor, sticking it into my code and thus setting up transaction boundaries. Between these boundary points, I could get Lazy Loading to work.

From the perspective of compliance with the Portlet Specification JSR-168, what Liferay has done maybe right. The spec clearly splits up each request into Action and Render phases. The Portal is supposed to enable multiple portlets to respond to each of these phases in parallel. Chances are Liferay is internally using a pool of threads and dispatching requests in parallel. The side effect is that frameworks written for traditional web applications where it is assumed that the same thread is involved through out the request gets messed up.

Why Liferay did not make any effort to fix this issue is beyond me. It sure gave me a lot of heart burn.

In my case I had the code separated into a service class, and that helped, because I was able to extend org.springframework.orm.hibernate3.HibernateAccessor. I setup the start point of the transaction boundary by this code. Created a method startTransaction to do so.

currentSession = SessionFactoryUtils.getSession(
getSessionFactory(), true
);
setFlushModeName("FLUSH_NEVER");
applyFlushMode(currentSession, true);
TransactionSynchronizationManager.bindResource(
getSessionFactory(), new SessionHolder(currentSession)
);


Corresponding end point was setup through another method
endTransaction.


SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(
getSessionFactory()
);
SessionFactoryUtils.closeSession(sessionHolder.getSession());

No comments: