sessionFactory建立一次除了beforeclass和afterclass,还有单例,static语句块两种方法
实体类:
package com.zzk.hibernate.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { private int id; private String name; private String title; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
测试类:
package com.zzk.hibernate.model; import static org.junit.Assert.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class TeacherTest { private static SessionFactory sf = null; @BeforeClass public static void beforeClass() { //防止出现Junit的“静默”BUG的方法一 try { sf = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @After public void tearDown() throws Exception { } @Test public void testTeacherSave() { Teacher t = new Teacher(); t.setId(1); t.setName("t1"); t.setTitle("中级"); Session session = sf.openSession(); session.beginTransaction();//执行操作 session.save(t); session.getTransaction().commit();//提交 session.close(); } //解决JUNIT"静默"BUG的方法二 // public static void main(String[] args) { // beforeClass(); // } // @AfterClass public static void afterClass() { sf.close(); } }