阅读418 返回首页    go 阿里云 go 技术社区[云栖]


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

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();
	}
	
}




最后更新:2017-04-02 17:28:39

  上一篇:go Android 怎么把imageview 转为Bitmap
  下一篇:go Android数据库(SqlLite)操作和db文件查看