Illegal attempt to associate a collection with two open sessions

Illegal attempt to associate a collection with two open sessions

When we are working with collections with spring and hibernate, you may end up with this exception while saving an object. Googling says this is a feature/bug of hibernate – hibernate is not versioning the collections as it does for other objects. Don’t know what it is in detail, but I should solve this right now. The suggested solution is to have  single session. The following the code that saves my object.

public class BaseDAO extends HibernateDaoSupport implements IBaseDAO {
.....
/* (non-Javadoc)
	 * @see com.eginnovations.license.dao.IBaseDAO#save(java.lang.Object)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly=false)
	public Object save(Object entity){
		Session session = super.getSession();
		Serializable save = session.save(entity);
		logger.debug("save:"+save.getClass()+" "+save+" "+entity);
		return save;
	}

..............
}

New session are getting opened in super.getsession() and session.save().

The problem is I have not implemented OpenSessionInViewFilter till now, so I don’t have the option to have the single session. So here is the entries added to the deployment descriptor web.xml.

	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

And this is the filter mapping.

<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>ERROR</dispatcher>
	</filter-mapping>

Go ahead!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s