用OpenSessionInViewInterceptor 的思路解决Hibernate Lazy

package com.iteye.common.test;

import junit.framework.TestCase;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public abstract class AbstractTestBean extends TestCase {

	protected ApplicationContext applicationContext;

	private SessionFactory sessionFactory;

	private Session session;

	protected void setUp() throws Exception {

		String configFile = "spring/*.xml";
		applicationContext = new ClassPathXmlApplicationContext(configFile);
		sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
		session = SessionFactoryUtils.getSession(sessionFactory, true);
		session.setFlushMode(FlushMode.NEVER);
		TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	}

	protected void tearDown() throws Exception {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		SessionFactoryUtils.releaseSession(session, sessionFactory);
	}
}


这是我的TestCase的基类,所有的TestCase继承这个类,就可以具备OpenSessionInView的功能。

你可能感兴趣的:(spring,Hibernate,xml,orm,JUnit)