閱讀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文件查看