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




目录
相关文章
|
9月前
|
XML Java 数据库连接
Hibernate与Spring整合实践实例
Hibernate与Spring整合实践实例
174 0
|
Java 数据库连接 数据库
spring整合hibernate的详细步骤
  Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibernate:     1.
1089 0
|
SQL XML Java
Hibernate基础配置
@Entity @Table(name = "teacher") // 指定该类对应的表明 public class Teacher {// 实体与 private int id; private String ...
935 0
|
SQL XML 缓存
mybatis与hibernate运行流程比较
mybatis与hibernate运行流程比较
119 0
mybatis与hibernate运行流程比较
|
9月前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
|
SQL 存储 XML
mybatis configuration 核心构建流程
mybatis configuration 核心构建流程
173 0

热门文章

最新文章