您的位置:首页 > 其它

Hibernate下搭建JUNIT的测试环境,使用beforeclass和afterclass实现sessionFactory建立一次

2012-05-16 18:32 736 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: