牛骨文教育服务平台(让学习变的简单)
博文笔记

spring hibernate 单元测试手动开启关闭session

创建时间:2017-11-03 投稿人: 浏览次数:322
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@ContextConfiguration(locations={"classpath*:hibernate-context.xml", "classpath*:spring.xml"})
public class TestRootApplication extends AbstractJUnit4SpringContextTests {

    protected Log log = LogFactory.getLog(getClass());
    public Log log = LogFactory.getLog(getClass());

    @Autowired
    private SessionFactory sessionFactory;
    private Session session;

    @Before
    public void openSession()  throws Exception {
        session = SessionFactoryUtils.getSession(sessionFactory, true);
        session.setFlushMode(FlushMode.MANUAL);
        TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session));
    }

    @After
    public void closeSession()  throws Exception {
        TransactionSynchronizationManager.unbindResource(sessionFactory);
        SessionFactoryUtils.releaseSession(session, sessionFactory);
    }

}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。