Results 1 to 2 of 2

Thread: NullPointerException when use HibernateDaoSupport

  1. #1
    Join Date
    Jun 2012
    Posts
    1

    Default NullPointerException when use HibernateDaoSupport

    Hi all,

    I'm student and i start to learning Spring framework with hibernate.

    I wonder where's my mistake in this code?

    Here is my applicationContext.xml:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
              p:location="/WEB-INF/jdbc.properties" />
    
        <bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource"
              p:driverClassName="${jdbc.driverClassName}"
              p:url="${jdbc.url}"
              p:username="${jdbc.username}"
              p:password="${jdbc.password}" />
    
        <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                    <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
                    <prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop>
                </props>
            </property>
            <property name="mappingResources">
                <list>
                    <value>demo/hbm/Account.hbm.xml</value>
                </list>
            </property>
        </bean>
    
        <!-- DAO -->
        <bean name="accountDao" class="demo.dao.AccountDaoImpl">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
        
        <bean name="baseDAO" class="demo.global.BaseDao">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
    
    
    
        
        <!-- BUS -->
        <bean name="accountBus" class="demo.bus.AccountBusImpl">
            <property name="accountDao" ref="accountDao"/>
        </bean>
    
    
        
        <!-- Servlet -->
        <bean id="AccountController" class="demo.controller.AccountController">
            <property name="accountBus" ref="accountBus"/>
        </bean>
    
        <!-- Abstract Spring Controller -->
        <bean id="AbstractAccountController" class="demo.controller.AbstractAccountController">
            <property name="baseDAO" ref="baseDAO"/>
        </bean>
    </beans>
    here is AbstractAccountController.java
    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package demo.controller;
    
    import demo.bus.AccountBus;
    import demo.bus.AccountBusImpl;
    import demo.dao.AccountDaoImpl;
    import demo.dto.Account;
    import demo.global.BaseDao;
    import java.util.List;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.AbstractController;
    
    /**
     *
     * @author DungND60190
     */
    public class AbstractAccountController extends AbstractController {
        private BaseDao baseDAO;
    
        public void setBaseDAO(BaseDao baseDAO) {
            this.baseDAO = baseDAO;
        }
    
        public AbstractAccountController() {
        }
        
        protected ModelAndView handleRequestInternal(
                HttpServletRequest request, 
                HttpServletResponse response) throws Exception {
       
            baseDAO = new BaseDao();
            List<Object> list = baseDAO.getAll(Account.class); // --> Null in this line.
            Account[] accList = new Account[list.size()];
            list.toArray(accList);
    
            return new ModelAndView("index", "accountList", accList);
    
        }
    
    
    
    }
    This is my baseDao.java
    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package demo.global;
    
    import java.io.Serializable;
    import java.util.List;
    import org.hibernate.Session;
    import org.springframework.dao.DataAccessException;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    /**
     *
     * @author Violet_Ink
     */
    public class BaseDao extends HibernateDaoSupport {
    
         public List<Object> getAll(Class cls) {
            List<Object> resultList = null;
            try {
                resultList = getHibernateTemplate().loadAll(cls);
            } catch (DataAccessException ex) {
                throw ex;
            }
            return resultList;
        }
    }
    This is my dispatcher-servlet.xml:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
        <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    
        <!--
        Most controllers will use the ControllerClassNameHandlerMapping above, but
        for the index controller we are using ParameterizableViewController, so we must
        define an explicit mapping for it.
        -->
        <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="mappings">
                <props>
                    <prop key="index.html">indexController</prop>
                </props>
            </property>
        </bean>
        
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix">
                  <value>/WEB-INF/jsp/page/</value>
              </property>
              <property name="suffix">
                  <value>.jsp</value>
              </property>
        </bean>
        
        <!--
        The index controller.
        -->
        <bean name="indexController"
              class="demo.controller.AbstractAccountController"/>
    
    </beans>
    This is my index.jsp
    Code:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Welcome to Spring Web MVC project</title>
        </head>
    
        <body>
           
            <p>Hello! This is the default welcome page for a Spring Web MVC project.</p>
            <p><i>To display a different welcome page for this project, modify</i>
                <tt>index.jsp</tt> <i>, or create your own welcome page then change
                    the redirection in</i> <tt>redirect.jsp</tt> <i>to point to the new
                    welcome page and also update the welcome-file setting in</i>
                <tt>web.xml</tt>.</p>
        </body>
        <table border="1">
            <thead>
                <tr>
                    <th>No.</th>
                    <th>User</th>
                    <th>pass</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                <c:forEach items="${accountList}" var="accList">
                <tr>
                    <td><c:out value="${accList.id}"></c:out></td>
                    <td><c:out value="${accList.username}"></c:out></td>
                    <td><c:out value="${accList.password}"></c:out></td>
                    <td><c:out value="${accList.email}"></c:out></td>
                </tr>
                </c:forEach>
            </tbody>
        </table>
    
    </html>
    Assume that All database, class Account and config of hibernate is correct. I use netbean 6.9.1 with tomcat 6.0.26

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    I suggest you take a nice close look at your controller...

    Code:
        protected ModelAndView handleRequestInternal(
                HttpServletRequest request, 
                HttpServletResponse response) throws Exception {
       
            baseDAO = new BaseDao();
            List<Object> list = baseDAO.getAll(Account.class); // --> Null in this line.
            Account[] accList = new Account[list.size()];
            list.toArray(accList);
    
            return new ModelAndView("index", "accountList", accList);
    What do you think happens here? You create a new instance of the bean and basically throw away the correctly configured one from the application context. Also you have a duplicate configured AbstractAccountController (why is it called that way anyway as it isn't abstract?!) and one doesn't set the baseDao.


    Some other overservations:
    • don't use HibernateDaoSupport/HibernateTemplate it should be considered deprecated as of Hibernate 3.0.1 (which was released in 2007). Use the session factory and the getCurrentSession method to get the transactional session.
    • don't mess around with the hibernate.current_session_context as that will break proper tx management.
    • You don't have transactions configured, add a HibernateTransactionManager and something to drive the transactions (see the transaction chapter in the reference guide).


    Also this question has been answered numerous times before (by me alone already) using the forum search will yield several results.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •