hibernate创建session报空指针异常版本 hibernate5.1.0 jboss4.3
package com.imooc.entity;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Test
public void testSaveStudents() {
Students s = new Students();//创建学生对象
s.setSid(1);
s.setSname("张三丰");
s.setGender("男");
s.setBirthday(new Date());
s.setAddress("武当山");
session.save(s);//将学生对象写入数据库
}
@Before
public void init(){
//创建配置对象并读取classpath下的配置文件hibernate.cfg.xml
Configuration config = new Configuration();
//创建serviceRegistry对象,hibernate中的任何配置和服务都必须在此对象中注册
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
ServiceRegistry serviceRegistry = ssrb.build();
//创建会话工厂对象
sessionFactory = config.configure().buildSessionFactory(serviceRegistry);
//开启会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@After
public void destroy(){
if(transaction!=null){
transaction.commit();//提交事务
if(session!=null){
session.close();//关闭会话
if(sessionFactory!=null){
sessionFactory.close();//关闭会话工厂
}
}
}
}
}