views:

207

answers:

1

Hi,

sometimes when testing some CRUD operations in my DAO classes using JUnit 4.5, Hibernate throws an exception:

org.hibernate.SessionException: Session is closed!

The session is not closed explicitly, so what happens?

Thanks

A: 

I use snippet listed below, and I didn't encounter any problems

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(){
       // 
    }
Maciek Kreft