关于 Hib工具类 sessionFactory 初始化空指针报错的问题

来源:6-3 后台注册接口编写-3

NickCharlie

2020-02-20

老师好,我按照老师的方法敲代码,jdk版本已经回退到8,在Hib工具类的初始化方法Init()的try catch里丢出了一个空指针错误,经过debug确定为

    private static void init() {
        // 从hibernate.cfg.xml文件初始化
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            // build 一个sessionFactory
            sessionFactory = new MetadataSources(registry)  // sessionFactory = null
                    .buildMetadata()
                    .buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();	// 执行了输出异常
            // 错误则打印输出,并销毁
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

这里出了异常直接转到catch里,sessionFactory为null,报空指针异常

报错
20-Feb-2020 18:18:30.744 涓ラ噸 [http-nio-8848-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [TechatApiServlet] in context with path [/Gradle___ink_techat___TechatWeb_1_0_SNAPSHOT_war] threw exception [java.lang.NullPointerException] with root cause
	java.lang.NullPointerException
		at ink.techat.web.push.utils.Hib.session(Hib.java:58)
		at ink.techat.web.push.factory.UserFactory.register(UserFactory.java:27)
		at ink.techat.web.push.service.AccountService.register(AccountService.java:24)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:74)
		at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
		at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
		at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:247)
		at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
		at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:388)
		at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:346)
		at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
		at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:337)
Hib工具类源代码 
package ink.techat.web.push.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.util.logging.Logger;

/**
 * Created by qiujuer
 * on 2017/2/17.
 */
public class Hib {
    private static final Logger LOGGER = Logger.getLogger(Hib.class.getName());
    // 全局SessionFactory
    private static SessionFactory sessionFactory;

    static {
        // 静态初始化sessionFactory
        init();
    }

    private static void init() {
        // 从hibernate.cfg.xml文件初始化
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            // build 一个sessionFactory
            sessionFactory = new MetadataSources(registry)
                    .buildMetadata()
                    .buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();
            // 错误则打印输出,并销毁
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

    /**
     * 获取全局的SessionFactory
     *
     * @return SessionFactory
     */
    public static SessionFactory sessionFactory() {
        return sessionFactory;
    }

    /**
     * 从SessionFactory中得到一个Session会话
     *
     * @return Session
     */
    public static Session session() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * 关闭sessionFactory
     */
    public static void closeFactory() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }
}

AccountService.java 源代码
package ink.techat.web.push.service;

import ink.techat.web.push.bean.api.account.RegisterModel;
import ink.techat.web.push.bean.card.UserCard;
import ink.techat.web.push.bean.db.User;
import ink.techat.web.push.factory.UserFactory;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * @author NickCharlie
 * 127.0.0.1/api/account/...
 */
@Path("/account")
public class AccountService {

    @POST
    @Path("/register")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public UserCard register(RegisterModel model){

        User user = UserFactory.register(model.getAccount(),
                model.getPassword(), model.getName());

        if(user != null){
            UserCard card = new UserCard();
            card.setName(user.getName());
            card.setPhone(user.getPhone());
            card.setSex(user.getSex());
            card.setIsFollow(true);
            card.setModifyAt(user.getUpdateAt());
            return card;
        }
        return null;
    }
}

hibernate.cfg.xml 除了更改了数据库地址和账号密码以及 mapping 映射以外,没有其他的更改。

写回答

1回答

Qiujuer

2020-02-20

建议核查一下hibernate.cfg.xml 文件与项目的文件存放的位置以及命名是否有差异。
错误是因为初始化的时候没有正确初始化导致的问题,这个问题一般是因为:hibernate.cfg.xml  文件读取失败导致的。

1
5
Qiujuer
回复
NickCharlie
从这里来看,是ownerId的model设置的不为空,但是实际创建的时候传入了空。可以看看这里是否需要,不需要设置为可为空,如需要则需调试看看为什么没有传入值。
2020-02-24
共5条回复

手把手开发完整的即时通讯App 客户端+服务端+MVP架构

客户端+服务端+MVP架构+封装思想+主流框架

1749 学习 · 872 问题

查看课程