关于Hibernate的自动生成HibernateSessionFactory使用疑惑

用Myeclipse自动生成HibernateSessionFactory类中

``` private static final ThreadLocal threadLocal = new ThreadLocal();
private static org.hibernate.SessionFactory sessionFactory;

private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry; 

static {
    try {
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Exception e) {
        System.err.println("%%%% Error Creating SessionFactory %%%%");
        e.printStackTrace();
    }
}
private HibernateSessionFactory() {
}

/**
 * Returns the ThreadLocal Session instance.  Lazy initialize
 * the <code>SessionFactory</code> if needed.
 *
 *  @return Session
 *  @throws HibernateException
 */
public static Session getSession() throws HibernateException {
    Session session = (Session) threadLocal.get();

    if (session == null || !session.isOpen()) {
        if (sessionFactory == null) {
            rebuildSessionFactory();
        }
        session = (sessionFactory != null) ? sessionFactory.openSession()
                : null;
        threadLocal.set(session);
    }

    return session;
}

/**
 *  Rebuild hibernate session factory
 *
 */
public static void rebuildSessionFactory() {
    try {
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Exception e) {
        System.err.println("%%%% Error Creating SessionFactory %%%%");
        e.printStackTrace();
    }
}

/**
 *  Close the single hibernate session instance.
 *
 *  @throws HibernateException
 */
public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);

    if (session != null) {
        session.close();
    }
}

/**
 *  return session factory
 *
 */
public static org.hibernate.SessionFactory getSessionFactory() {
    return sessionFactory;
}
/**
 *  return hibernate configuration
 *
 */
public static Configuration getConfiguration() {
    return configuration;
}
那我应该在Junit测试类中怎么使用

public class uernameTest {
@Before//初始化方法
public void init(){

}

@Test
public void testSaveUser(){

}

@After//释放资源
public void destory(){

}

}



2个回答

直接调用 getSession() 获取session 就好了 关闭也是一样

谢谢各位老哥们,小弟已经自己摸索出来怎么用了,真是很方便~!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐