使用JUnit测试Hibernate:“会话已关闭”异常

时间:2010-04-04 04:26:14

标签: hibernate junit

有时在使用JUnit 4.5在我的DAO类中测试一些CRUD操作时,Hibernate会抛出异常:

org.hibernate.SessionException:会话已关闭!

会话没有明确关闭,所以会发生什么?

由于

2 个答案:

答案 0 :(得分:1)

我使用下面列出的代码段,我没有遇到任何问题

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.*;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ComponentsTest {
    private static SessionFactory sf;
    private static Session s;
    private static Transaction tx;

    @BeforeClass
    public static void setUp() {
        sf = new AnnotationConfiguration().configure().buildSessionFactory();
    }

    @AfterClass
    public static void tearDown() {
        sf.close();
    }

    @Before
    public void open() {
        s = sf.openSession();
        tx = s.beginTransaction();
    }

    @After
    public void close() {
        tx.commit();
        s.close();
    }
    @Test
    public void testSth(){
       // 
    }

答案 1 :(得分:1)

假设您的事务管理器设置正确,以下代码将使您的会话保持打开状态:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext*.xml")
public class SpringTest {

    @Autowired private MyObjectDao myObjectDao;

    @Test
    @Transactional
    public void test() throws IOException {
        MyObject object = myObjectDao.find(objectId);
        object.setProperty("propertyValue");
        MyObject savedObject = myObjectDao.save(object);
        assertEquals(object.getProperty(), savedObject.getProperty());
    }
}