package com.javaeye.jert.service.test;
import junit.framework.TestCase;
import net.sf.hibernate.FlushMode;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate.SessionFactoryUtils;
import org.springframework.orm.hibernate.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* @author Quake Wang
* @since 2004-12-21
* @version $Revision: 1.1 $
*/
public abstract class TestService extends TestCase {
protected ApplicationContext context;
protected void setUp() throws Exception {
context = getContext();
openSession();
super.setUp();
}
protected abstract ApplicationContext getContext();
private void openSession() {
SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
Session hibSession = SessionFactoryUtils.getSession(sessionFactory, true);
hibSession.setFlushMode(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(hibSession));
}
protected void tearDown() throws Exception {
super.tearDown();
closeSession();
}
private void closeSession() {
SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory);
}
}