Neha
Neha

Reputation: 109

NullPointerException in sessionFactory.openSession

I'm developing a web application using Spring Hibernate. At there I have a method in DAO class.

When I call it through a jsp file it works well. But When I call it through servlet it gives a NullPointerException. Below I put the method.

@Autowired
private SessionFactory sessionFactory;

@SuppressWarnings("unchecked")
public List<Employee> listEmployees() {

    Session session = sessionFactory.openSession();//line 95
    Criteria crit= session.createCriteria(Employee.class);
    crit.add(Restrictions.eq("EmployeeId",2 ));
    List<Employee> employeelist= crit.list();
    session.close();
    return employeelist;

}

Below is how I call it.

public void getConfirm(HttpServletRequest request, HttpServletResponse response) { 

Logger.getLogger(this.getClass()).warning("Inside Confirm Servlet");  
    response.setContentType("text/html"); 

    // do some works

    EmployeeDao employeeDao=new EmployeeDao();
    employeeDao.listEmployees();         //line 55

    }

This is my sessionFactory configuration

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>abc.model.Employee</value>
            </list>
        </property>
        <property name="hibernateProperties" >

            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>             
            </props>
        </property>
    </bean>

And This is the error

SEVERE: Servlet.service() for servlet [ConfirmServlet] in context with path[/Spring3Hibernate] threw exception
    java.lang.NullPointerException
    at abc.dao.EmployeeDao.listEmployees(EmployeeDao.java:95)
    at abc.mail.ConfirmServlet.getConfirm(ConfirmServlet.java:55)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Could you please tell me how to solve this because I want to call it through servlet.

Upvotes: 3

Views: 17537

Answers (3)

Bishal Paudel
Bishal Paudel

Reputation: 1946

For me, the mapping attribute in hibernate.cfg.xml was pointing to incorrect Model.

Upvotes: 0

Debojit Saikia
Debojit Saikia

Reputation: 10632

When I call it through a jsp file it works well.

Its working because you have this statement defined in your DAO:

@Autowired
private SessionFactory sessionFactory;

And the DAO instance on which the listEmployees method was called is a Spring managed bean and the Spring managed SessionFactory that you have defined in your configuration file has already been injected into your DAO bean.

But When I call it through servlet it gives a NullPointerException

This is not working:

EmployeeDao employeeDao=new EmployeeDao();
employeeDao.listEmployees();  

Because the EmployeeDao instance on which listEmployees is being called is not a Spring managed bean. Its just a new instance of EmployeeDao. So the SessionFactory instance that you have in your EmployeeDao is null.

Now, if you want to inject your Spring managed EmployeeDao into your Servlet, you can do this by overriding the Servlet's init method as below:

private EmployeeDao ed;
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
    ed = (EmployeeDao) context.getBean("employeeDao");
}

You can now re-write getConfirm method to this:

public void getConfirm(HttpServletRequest request, HttpServletResponse response) { 

Logger.getLogger(this.getClass()).warning("Inside Confirm Servlet");  
    response.setContentType("text/html"); 

    // do some works

    //EmployeeDao employeeDao=new EmployeeDao();
    employeeDao.listEmployees();         //line 55

    }

EDIT:

Make these entries into your web.xml:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/your-spring-config-file.xml
    </param-value>
</context-param>

Upvotes: 4

Kamlesh Meghwal
Kamlesh Meghwal

Reputation: 4972

Include below line of code before line 95. Assuming that you havent created SessionFactory object

SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
//Your operation
Session.getTransaction().commit();

Upvotes: 0

Related Questions