问答详情
源自:1-11 通过Hibernate API编写访问数据库的代码

请高手帮我解决一下空指针异常

代码如下根老师的差不多,但测试运行时分别在 创建会话工厂对象sessionFactory = config.buildSessionFactory(serviceRegistry)和释放资源时的transaction.commit()报了两个空指针异常,有高手能帮我解决一下吗

提问者:vvflag 2016-09-02 21:23

个回答

  • 自小生来神气壮
    2016-09-02 21:59:07
    已采纳

    代码和错误信息贴出来啊

  • vvflag
    2016-09-03 20:52:12

    public class UsersTest {

    private SessionFactory sessionFactory = null;

    private Session session = null;

    private Transaction transaction = null;

    @Before

    public void init(){

    //1.创建配置对象

    Configuration config = new Configuration().configure();

    //2.创建服务注册对象

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();

    //3.创建会话工厂对象

    sessionFactory = config.buildSessionFactory(serviceRegistry);

    //4.创建会话对象

    session = sessionFactory.openSession();

    //5.开启事务

    transaction = session.beginTransaction();

    }

    @Test

    public void test(){

    Users user = new Users(2, "root", "abcd");

    session.save(user);

    }

    @After

    public void destroy(){

    transaction.commit();

    session.close();

    sessionFactory.close();

    }

    }