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 ha开发者_运维技巧ppens?
Thanks
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(){
//
}
Assuming your transaction manager is setup correctly, the following code will keep your session open:
@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());
}
}
精彩评论