Spring+Hibernate延遲加載測試基類(lèi)
import junit.framework.TestCase;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public abstract class AbstractTest extends TestCase{
private static SessionFactory sessionFactory ;
private static ApplicationContext ctx;
public void setUp() throws Exception {
ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
sessionFactory = (SessionFactory) getBean("sessionFactory");
Session s = sessionFactory.openSession();
TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(s));
}
protected static Object getBean(String beanName) {
return ctx.getBean(beanName);
}
public void tearDown() throws Exception {
SessionHolder holder = (SessionHolder) TransactionSynchronizationManager
.getResource(sessionFactory);
Session s = holder.getSession();
s.flush();
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(holder.getSession());
}
}
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。