Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Code Block
titleOpenSessionBackgroundProcess.java
borderStylesolid
import net.sf.hibernate.FlushMode;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;

import org.springframework.orm.hibernate.SessionFactoryUtils;
import org.springframework.orm.hibernate.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.opensymphony.webwork.interceptor.BackgroundProcess;
import com.opensymphony.xwork.ActionInvocation;

/**
 * The OpenSessionBackgroundProcess, when instantiated with a
 * HibernateSessionFactory, will open a session, enable Spring's transaction
 * management capabilities, and bind the Session to the background thread.
 * 
 */
public class OpenSessionBackgroundProcess extends BackgroundProcess {

	SessionFactory sessionFactory;

	Session openSession;

	public class OpenSessionBackgroundProcess extends BackgroundProcess {

	SessionFactory sessionFactory;
	Session openSession;
        protected boolean initializationComplete = false;
        private Object lock = new Object(); // used for synchronization

	public OpenSessionBackgroundProcess(String name,
			ActionInvocation invocation, int threadPriority,
			SessionFactory factory) {
		super(name, invocation, threadPriority);
		this.sessionFactory = factory;
                initializationComplete = true;
                synchronized (lock) {
                        lock.notify();
                }
	}

	protected void beforeInvocation() throws Exception {
                while (!initializationComplete) {
                        try {
                                synchronized (lock) {
                                        lock.wait(100);
                                }
                       } catch (InterruptedException e) {
                               // behavior ignores cause of re-awakening.
                       }
                }
		openSession = SessionFactoryUtils.getSession(sessionFactory, true);
		openSession.setFlushMode(FlushMode.NEVER);
		TransactionSynchronizationManager.bindResource(sessionFactory,
				new SessionHolder(openSession));
		super.beforeInvocation();
	}

	protected void afterInvocation() throws Exception {
		super.afterInvocation();
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		SessionFactoryUtils
				.closeSessionIfNecessary(openSession, sessionFactory);
	}


}