一个hibernate4.2中用junit4测试小例子

实体类teacher

package com.luhy.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;
	}
	
}

junit4测试类TeacherTest

package com.luhy.hibernate.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.luhy.hibernate.model.Teacher;

public class TeacherTest {

	private static SessionFactory sessionFactory = null;
	
	@BeforeClass
	public static void beforeClass(){
		Configuration cfg = new Configuration().configure();
        ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		sessionFactory = cfg.buildSessionFactory(serviceRegistry);
	}
	@Test
	public void testTeacherSave() {
		Teacher t = new Teacher();
		t.setId(2);
		t.setName("在");
		t.setTitle("oolk");
        Session session = sessionFactory.openSession();
        session.beginTransaction();               //事务开启
        session.save(t);                             //保存对象
        session.getTransaction().commit();
        session.close();    
	}
	
	@AfterClass
	public static void afterClass(){
		sessionFactory.close();
	}

}

工程目录结构如下图


一个hibernate4.2中用junit4测试小例子_第1张图片

写这个例子主要是想让新手在初学时需要注意一些技巧,像源码目录test,一般用来存放需要测试的类,还有测试类teacherTest中的 静态方法 beforeClass 和 afterClass的用法

你可能感兴趣的:(java,Hibernate,log4j,String,JUnit)