Home > database >  getting NullPointerException while calling SessionFactory in JSP page
getting NullPointerException while calling SessionFactory in JSP page

Time:09-21

While calling qs.getSubList() method occurring below exception. don't know why it is showing error, while calling same method from other class its work perfectly and return Question list.

   java.lang.NullPointerException: Cannot invoke "org.hibernate.SessionFactory.openSession()" because "this.sessionFactory" is null

queType.jsp

<%@page import="java.util.List"%>
<%@page import="com.guru.onlineexam.entity.Question"%>
<%@page import="com.guru.onlineexam.service.QuestionService"%>
<%
    QuestionService qs = new QuestionService();
    List<Question> qList = qs.getSubList();
    out.println(qList);
%>

QuestionService.java

@Service
public class QuestionService {

    @Autowired
    MainDao mainDao;

    @Autowired
    SessionFactory sessionFactory;

 public List<Question> getSubList() {
        // Session session = mainDao.getSession();
        Session session = sessionFactory.openSession();
        String query = "SELECT DISTINCT que_subject FROM Question";
        Query q = session.createQuery(query);
        List<Question> sublist = q.getResultList();

        return sublist;
    }
}

CodePudding user response:

java.lang.NullPointerException: Cannot invoke "org.hibernate.SessionFactory.openSession()" because "this.sessionFactory" is null

It's looks to me that you need to configure sessionFactory for 'queType.jsp'

CodePudding user response:

It's showing you the error because you use the instance of QuestionService made by yourself and not by Spring.

To make properties of the service initialized you need to get the instance ftom the Spring context or pass it to the autowiring factory.

Although, scriptlets in JSP are descouaraged, you should write something like this in your controller component

QuestionService qs = AppContext.getBean(QuestionService.class);

then check the property of your sessionFactory. It should not be null.

  • Related