gpt4 book ai didi

java - 为什么 Hibernate session 提取在此代码段中失败?

转载 作者:行者123 更新时间:2023-11-29 09:12:11 27 4
gpt4 key购买 nike

我正在试验 Hibernate 4.1.2。

编写了以下类来帮助我使用新的 ServiceRegistry 方法获得 session

============================================= ======

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。

谁能解释一下这种行为?

最佳答案

正如我在评论中所说,工厂已关闭。也许在 @AfterClass 部分关闭它?

关于java - 为什么 Hibernate session 提取在此代码段中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com