Reputation: 255
I am getting following exception. The exception always comes back to the line:
Session session = HibernateUtil.getDefaultSession().openSession();
Here is a trimmed version of the 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)
My HibernateUtil looks like--
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;
}
And my DAO looks like something
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();
}
}
I have been trying numerous different things and Have tried as stackoverflow suggested however and still get same null-pointer at same line of code..
My folder structure:
Upvotes: 0
Views: 891
Reputation: 719576
You say that the exception is thrown in this line:
Session session = HibernateUtil.getDefaultSession().openSession();
Since HibernateUtil.getDefaultSession
is a static method, this means that getDefaultSession()
is returning null
.
Then we look at getDefaultSession()
and it is simply returning the the value of factory
. ThisgetDefaultSession implies that factory
is null
. How come? Because your code is not initializing it!!
I can see you are attempting to initialize it in a constructor. But that can only work if you call the constructor. And you don't!
A better solution is to use a static method to do the initialization; 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;
}
}
Upvotes: 2