我正在尝试使用 Hibernate 4.1.2。
编写了以下课程以帮助我使用新的 ServiceRegistry 方法获得会话
==================================================== ===
package com.debaself.samples;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class SessionFetch {
private static SessionFactory sessionFactory = null;
public SessionFactory getSessionFactory(){
if(sessionFactory == null){
Configuration cfg = new AnnotationConfiguration().addResource("hibernate.cfg.xml").configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
return sessionFactory ;
}
public Session getSession(){
return getSessionFactory().openSession();
}
}
================================================
现在我写了一个测试
================================================
public class SessionFetchTest {
@Test
public void getSessionFactoryTest(){
SessionFetch fetch = new SessionFetch();
SessionFactory factory = fetch.getSessionFactory();
assertNotNull(factory);
assert(!factory.isClosed());
factory.close();
}
@Test
public void getSessionTest(){
SessionFetch fetch = new SessionFetch();
Session session = fetch.getSession();
assert(session.isOpen());
assert(session.isConnected());
}
}
====================================================
奇怪的是
当我单独运行测试方法时,两个测试都成功了。但是当我一次性运行它们时,getSessionTest() 总是失败并抛出 UnknownServiceException。
谁能解释一下这种行为?