import java.util.Date;
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.After;
import org.junit.Before;
import org.junit.Test;
import com.imooc.hibernate.Students;
//测试类
public class StudentsTest {
private SessionFactory sessionFctory;
private Session session;
private org.hibernate.Transaction transaction;
@Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务 注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
//创建会话工厂对象
sessionFctory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFctory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@After
public void destroy(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFctory.close();//关闭会话工厂
}
@Test
public void testSaveStudents(){
//生成学生对象
Students s = new Students(1,"小明","女",new Date(),"石家庄");
session.save(s);//保存对象进数据库
}
}