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();//关闭会话工厂
}
}
}
}
}
我的问题是没有通过spring 的bean 直接调用了dao层的实体类 所以空指针
package hibernate_test1; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; 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; public class HibernateTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init() { // 创建配置对象 Configuration configuration = new Configuration().configure(); // 创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); //创建会话工厂对象 sessionFactory = configuration.buildSessionFactory(serviceRegistry); //创建会话对象 session = sessionFactory.openSession(); //开启事务 transaction = session.beginTransaction(); } @Test public void test() { User user = new User("A1","张三",20,new Date()); session.save(user); } @After public void destroy() { //提交事务 transaction.commit(); //关闭资源 session.close(); sessionFactory.close(); } }
@Before public void init(){ //创建配置对象并读取classpath下的配置文件hibernate.cfg.xml Configuration config = new Configuration(); //创建serviceRegistry对象,hibernate中的任何配置和服务都必须在此对象中注册 StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(config.getProperties()); //这里这里看这里!! ServiceRegistry serviceRegistry = ssrb.buildServiceRegistry();
注册对象不对,应该用buildServiceRegistery()方法,而不是用build()方法