HibernateUtil中的java.lang.NullPointerException

时间:2017-06-23 12:30:13

标签: java hibernate nullpointerexception

我得到以下异常。异常总是回到这一行:

      Session session = HibernateUtil.getDefaultSession().openSession();

这是stacktrace的修剪版本

SEVERE: Servlet.service() for servlet [jsp] in context with path [/examAdmin] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at dao.AddCartDAO.deleteUnknownCartProduct(AddCartDAO.java:105)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:396)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

我的HibernateUtil看起来像 -

    public class HibernateUtil {
        private static SessionFactory factory;

        @SuppressWarnings("deprecation")
       private HibernateUtil() {
       try {
            factory = new Configuration().configure().buildSessionFactory();
           } catch (Throwable ex) {
           System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex);
        }
  }

public static SessionFactory getDefaultSession() {
       return factory;
}

我的DAO看起来像是

 public void deleteUnknownCartProduct(String uid, String status) {
  Session session = HibernateUtil.getDefaultSession().openSession();
  Transaction tx = null;
  try {
     tx = session.beginTransaction();
     String hql = "Delete AddCart a where a.userid=:userid and a.status=:status";
     Query query = session.createQuery(hql);
     query.setParameter("userid", uid);
     query.setParameter("status", status);
     query.executeUpdate();
     tx.commit();
} catch (HibernateException e) {
     if (tx != null)
     tx.rollback();
     e.printStackTrace();
} finally {
     session.close();
}
}

我一直尝试了很多不同的东西,并尝试过stackoverflow但是仍然在相同的代码行中得到相同的空指针..

我的文件夹结构:

enter image description here

1 个答案:

答案 0 :(得分:2)

你说在这一行引发了异常:

   Session session = HibernateUtil.getDefaultSession().openSession();

由于HibernateUtil.getDefaultSession是一种静态方法,这意味着getDefaultSession()正在返回null

然后我们查看getDefaultSession(),它只是返回factory的值。 ThisgetDefaultSession意味着factorynull。怎么会?因为你的代码没有初始化!!

我可以看到你试图在构造函数中初始化它。但是,只有当你调用构造函数时,这才有效。而你却没有!

更好的解决方案是使用静态方法进行初始化; e.g。

public class HibernateUtil {
    private static SessionFactory factory = initFactory();

    @SuppressWarnings("deprecation")
    private static initFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getDefaultSession() {
        return factory;
    }
}