Tuesday, November 23, 2010

OpenSessionInViewFilter singleSession=false, Illegal attempt to associate a collection with two open sessions

In previous configurations I've been setting the singleSession=true in the OpenSessionInViewFilter provided by spring. This parameter binds a Hibernate session to the request. However, this proved to be problematic in our scenario because we were caching the POJO entities in a cache store that lives outside of Hibernate's caching mechanisms. Why we are having another caching mechanism is irrelevant, but for sanity sake, I'll just say that we have different datasources that are combined into a single entity, which makes caching important for performance reasons.

Since this cache store is accessible by all incoming requests, POJO's that were added to the cache by previous requests, were still associated with the session bound to the previous request (that were lazily loaded). In an asynchronous environment, this led to the following Hibernate exception: Illegal attempt to associate a collection with two open sessions

To resolve this issue, I needed a way for multiple requests to share the same object loaded from the cache store. That is, I needed a way to unbound the session to the request and allow for multiple sessions within a single request. To do this, I changed the singleSession=true for the OpenSessionInViewFilter.

The thing to be aware of is now all data accesses should be wrapped in Transactions. To do this I used spring's annotations:


@Transactional(propagation=Propagation.REQUIRED, readOnly=false)public class FedoraPoddObjectDAOImpl extends AbstractFedoraDAOImpl<PoddObject> implements PoddObjectDAO

1 comment:

  1. Hi,
    I found your post is very informative. The article is professionally written and I feel like the author knows the subject very well.Keep it that way.will we talk in this weekend through the email??


    Nick
    E:- hire.netprogrammer.com@gmail.com

    ReplyDelete