Henri Blog

Study and Share knowledge

Simple CRUD – SpringMVC & Hibernate3

with 37 comments

It’s been 5 months as I’ve been working with Java Technology. Yes, I’m just a newbie. I’ve been working as bug fixing support team for medical system which is built using struts 1, spring Ioc, and hibernate. It’s painful for me because the legacy code is huge and almost with no comment. In reality I almost never do coding with underlying framework but medical system framework itself. Although it’s painful it’s a good starting point for me to learn Java Technology.

In idle time I encourage myself to learn other java technology and try to put it in code at weekend. For this opportunity I want to share creating simple CRUD application using SpringMVC and Hibernate3. Simple CRUD application that we’re going to build only consist one entity class (Person). Actually what we’re going to build is similar to Simple CRUD – CodeIgniter. Let’s begin.

  1. Database schema (MySql 5). run this script.
    CREATE DATABASE crud;
    
    GRANT ALL ON crud.* TO crud@localhost IDENTIFIED BY 'password';
    
    USE crud;
    CREATE TABLE tbl_person
    (
      id bigint auto_increment PRIMARY KEY,
      name varchar(50),
      gender char(1),
      dob date
    );
    
    INSERT tbl_person (name,gender,dob) VALUES('henrihnr', 'm', '1985-09-09');
    INSERT tbl_person (name,gender,dob) VALUES('name_001', 'm', '1990-01-01');
    INSERT tbl_person (name,gender,dob) VALUES('name_002', 'f', '2000-01-01');
    INSERT tbl_person (name,gender,dob) VALUES('name_003', 'm', '2000-02-02');
    INSERT tbl_person (name,gender,dob) VALUES('name_005', 'm', '2000-04-04');
  2. web.xml
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
    <!-- Front Controller -->
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>2</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.html</url-pattern>
        </servlet-mapping>
    <!-- end of Front Controller -->
  3. applicationContext.xml
        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
              p:location="/WEB-INF/jdbc.properties" />
    
        <bean id="dataSource"
              class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close"
              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="mappingResources">
                  <list>
                      <value>training/springmvc/crud/model/person.hbm.xml</value>
                  </list>
              </property>
              <property name="hibernateProperties">
                  <value>hibernate.dialect=org.hibernate.dialect.MySQLDialect</value>
              </property>
        </bean>
    
        <!-- Transaction Manager -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
    
        <!-- Service -->
        <bean id="personService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
            <property name="target">
                <bean class="training.springmvc.crud.service.PersonServiceImpl">
                    <property name="personDAO" ref="personDAO"/>
                </bean>
            </property>
            <property name="transactionAttributes">
                <props>
                    <prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
                    <prop key="*">PROPAGATION_REQUIRED</prop>
                </props>
            </property>
        </bean>
    
        <!-- DAO -->
        <bean id="personDAO" class="training.springmvc.crud.dao.PersonDAOHib"
            p:sessionFactory="sessionFactory"
            p:sessionFactory-ref="sessionFactory"/>
  4. dispatcher-servlet.xml
    <!-- Action Handling -->
        <!-- BeanNameUrlHandlerMapping
            This configuration is optional because BeanNameUrlHandlerMapping is the default handler.
            In case no handler mapping is found in the web application context, SpringMVC will create an instance of BeanNameUrlHandlerMapping.
        -->
        <bean name="beanNameUrlHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!-- end of Action Handling -->
    
    
    <!-- View Handler -->
        <!-- InternalResourceViewResolver
        The InternalResourceViewResolver class can determine the physical view in the web application archive given the logical view name.
        -->
        <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/jsp/"
              p:suffix=".jsp" />
    <!-- end of View Handler -->
    
    
    <!-- Page Controller -->
        <bean name="/index.html"
              class="training.springmvc.crud.controller.IndexController"
              p:personService="personService"
              p:personService-ref="personService"/>
    
        <bean name="/view.html"
              class="training.springmvc.crud.controller.ViewPersonController"
              p:personService="personService"
              p:personService-ref="personService"/>
    
        <bean name="/add.html"
              class="org.springframework.web.servlet.mvc.ParameterizableViewController"
              p:viewName="personEdit"/>
    
        <bean name="/update.html"
              class="training.springmvc.crud.controller.UpdatePersonController"
              p:personService="personService"
              p:personService-ref="personService"/>
    
        <bean name="/save.html"
              class="training.springmvc.crud.controller.SavePersonController"
              p:personService="personService"
              p:personService-ref="personService"/>
    
        <bean name="/delete.html"
              class="training.springmvc.crud.controller.DeletePersonController"
              p:personService="personService"
              p:personService-ref="personService"/>
    <!-- end of Page Controller -->
  5. entity class (POJO)
    public class Person implements Serializable {
    
        private Long id;
        private String name;
        private Character gender;
        private Date dob;
    
        public Person(){}
    
        // tricky method to parse form object to POJO
        public void setDob_(String dob_) throws Exception{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
            Date date = simpleDateFormat.parse(dob_);
            setDob(date);
        }
    
        // setters and getters
    
  6. hibernate mapping
    <class name="training.springmvc.crud.model.Person" schema="crud" table="tbl_person">
        <id column="id" name="id">
          <generator class="native"/>
        </id>
        <property column="name" name="name"/>
        <property column="gender" name="gender"/>
        <property column="dob" name="dob"/>
      </class>
  7. Page Controller.
    IndexController.java

    public class IndexController implements Controller {
    
        private PersonService personService;
        public void setPersonService(PersonService personService) {
            this.personService = personService;
        }
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map model = new HashMap();
            PagedListHolder pagedListHolder = (PagedListHolder) request.getSession().getAttribute("personList");
    
            if(pagedListHolder == null){
                pagedListHolder = new PagedListHolder(personService.getPersonList());
            }
            else{
                String page = (String) request.getParameter("page");
                if("next".equals(page)){
                    pagedListHolder.nextPage();
                }
                else if("previous".equals(page)){
                    pagedListHolder.previousPage();
                }
            }
    
            request.getSession().setAttribute("personList", pagedListHolder);
            model.put("personList", pagedListHolder);
            return new ModelAndView("index", model);
        }
    
    }

    ViewPersonController.java

    public class ViewPersonController implements Controller{
    
        private PersonService personService;
        public void setPersonService(PersonService personService) {
            this.personService = personService;
        }
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map model = new HashMap();
    
            Long id = Long.parseLong(request.getParameter("personId"));
            Person person = personService.getPerson(id);
    
            model.put("title", "Person Details");
            model.put("person", person);
            return new ModelAndView("personView", model);
        }
    
    }

    UpdatePersonController.java

    public class UpdatePersonController implements Controller{
    
        private PersonService personService;
        public void setPersonService(PersonService personService) {
            this.personService = personService;
        }
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map model = new HashMap();
    
            Long id = Long.parseLong(request.getParameter("personId"));
            Person person = personService.getPerson(id);
    
            model.put("title", "Update Person");
            model.put("person", person);
            return new ModelAndView("personEdit",model);
        }
    
    }

    SavePersonController.java

    public class SavePersonController extends AbstractCommandController{
    
        private PersonService personService;
        public void setPersonService(PersonService personService) {
            this.personService = personService;
        }
    
        public SavePersonController(){
            this.setCommandClass(Person.class);
        }
    
        @Override
        protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object form, BindException errors) throws Exception {
            Map model = new HashMap();
    
            Person person = (Person) form;
            personService.savePerson(person);
    
            request.getSession().setAttribute("personList", null);
    
            model.put("title","Update Person");
            model.put("person",person);
            return new ModelAndView("personEdit", model);
        }
    
    }

    DeletePersonController.java

    public class DeletePersonController implements Controller{
    
        private PersonService personService;
        public void setPersonService(PersonService personService) {
            this.personService = personService;
        }
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map model = new HashMap();
    
            Long id = Long.parseLong(request.getParameter("personId"));
            personService.deletePerson(id);
    
            PagedListHolder pagedListHolder = (PagedListHolder) request.getSession().getAttribute("personList");
    
            List personList = pagedListHolder.getSource();
            for(Iterator iterator = personList.iterator(); iterator.hasNext();){
                Person person = (Person) iterator.next();
                if(person.getId().equals(id)){
                    personList.remove(person);
                    break;
                }
            }
            pagedListHolder.setSource(personList);
    
            request.getSession().setAttribute("personList", pagedListHolder);
            model.put("personList", pagedListHolder);
            return new ModelAndView("index",model);
        }
    
    }
  8. Service (Facade).
    PersonService.java

    public interface PersonService {
    
        public List getPersonList();
    
        public Person getPerson(Long id);
    
        public void savePerson(Person person);
    
        public void deletePerson(Long id);
    }

    PersonServiceImpl.java

    public class PersonServiceImpl implements PersonService{
    
        private PersonDAO personDAO;
        public void setPersonDAO(PersonDAO personDAO) {
            this.personDAO = personDAO;
        }
    
        public List getPersonList() {
            return personDAO.getPersonList();
        }
    
        public Person getPerson(Long id){
            return personDAO.getPerson(id);
        }
    
        public void savePerson(Person person) {
            personDAO.savePerson(person);
        }
    
        public void deletePerson(Long id) {
            personDAO.deletePerson(id);
        }
    
    }
  9. DAO.
    PersonDAO.java

    public interface PersonDAO {
    
        public List getPersonList();
    
        public Person getPerson(Long id);
    
        public void savePerson(Person person);
    
        public void deletePerson(Long id);
    }

    PersonDAOHib.java

    public class PersonDAOHib extends HibernateDaoSupport implements PersonDAO{
    
        public List getPersonList(){
            return getHibernateTemplate().find("from Person");
        }
    
        public Person getPerson(Long id){
            return (Person) getHibernateTemplate().get(Person.class, id);
        }
    
        public void savePerson(Person person){
            this.getHibernateTemplate().saveOrUpdate(person);
        }
    
        public void deletePerson(Long id){
            getHibernateTemplate().delete(getPerson(id));
        }
    }
  10. JSP files
    index.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Simple CRUD - SpringMVC and Hibernate3</title>
        <link href="style/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div class="content">
            <h1>Simple CRUD - SpringMVC and Hibernate3</h1>
            <div class="paging">
              <c:if test="${!personList.firstPage}">
                <a href="index.html?page=previous"><b>&lt;&lt; Prev</b></a>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              </c:if>
              <c:if test="${!personList.lastPage}">
                <a href="index.html?page=next"><b>Next &gt;&gt;</b></a>
              </c:if>
            </div>
            <div class="data">
                <table border="0" cellpadding="4" cellspacing="0">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Gender</th>
                        <th>Date of Birth (dd-mm-yyyy)</th>
                        <th>Actions</th>
                    </tr>
                  <c:forEach var="person" items="${personList.pageList}">
                    <tr>
                        <td>${person.id}</td>
                        <td>${person.name}</td>
                        <td>
                            <c:choose>
                                <c:when test="${person.gender=='m'}">
                                    Male
                                </c:when>
                                <c:when test="${person.gender=='f'}">
                                    Female
                                </c:when>
                            </c:choose>
                        </td>
                        <td><fmt:formatDate dateStyle="full" pattern="dd-MM-yyyy" value="${person.dob}"/></td>
                        <td>
                            <a href="view.html?personId=${person.id}" class="view">view</a>
                            <a href="update.html?personId=${person.id}" class="update">update</a>
                            <a href="delete.html?personId=${person.id}" class="delete">delete</a>
                        </td>
                    </tr>
                  </c:forEach>
                  <c:if test="${personList.nrOfElements == 0}">
                    <tr><td colspan="5">No Person Data</td></tr>
                  </c:if>
                </table>
            </div>
            <br />
            <a href="add.html" class="add">add new person</a>
        </div>
    </body>
    </html>

    personView.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Simple CRUD - SpringMVC and Hibernate3</title>
        <link href="style/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div class="content">
            <h1>${title}</h1>
            <div class="data">
                <table>
                    <tr>
                        <td width="30%">ID</td>
                        <td>${person.id}</td>
                    </tr>
                    <tr>
                        <td valign="top">Name</td>
                        <td>${person.name}</td>
                    </tr>
                    <tr>
                        <td valign="top">Gender</td>
                        <td>
                            <c:choose>
                                <c:when test="${person.gender=='m'}">
                                    Male
                                </c:when>
                                <c:when test="${person.gender=='f'}">
                                    Female
                                </c:when>
                            </c:choose>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">Date of birth (dd-mm-yyyy)</td>
                        <td><fmt:formatDate dateStyle="full" pattern="dd-MM-yyyy" value="${person.dob}"/></td>
                    </tr>
                </table>
            </div>
            <br />
            <a href="index.html" class="back">back</a>
        </div>
    </body>
    </html>

    personEdit.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Simple CRUD - SpringMVC and Hibernate3</title>
        <link href="style/style.css" rel="stylesheet" type="text/css" />
        <link href="style/calendar.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="script/calendar.js"></script>
    </head>
    <body>
        <div class="content">
            <h1><c:out value="${title}" default="Add New Person"/></h1>
            <form method="post" action="save.html">
            <div class="data">
                <table>
                    <tr>
                        <td width="30%">ID</td>
                        <td><input type="text" name="id" disabled="disable" class="text" value="${person.id}"/></td>
                            <input type="hidden" name="id" value="${person.id}"/>
                    </tr>
                    <tr>
                        <td valign="top">Name</td>
                        <td><input type="text" name="name" class="text" value="${person.name}"/>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">Gender</td>
                        <td><input type="radio" name="gender" value="m" <c:if test="${person.gender=='m'}">checked</c:if>/> Male
                            <input type="radio" name="gender" value="f" <c:if test="${person.gender=='f'}">checked</c:if>/> Female
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">Date of birth (dd-mm-yyyy)</td>
                        <td><input type="text" name="dob_" onclick="displayDatePicker('dob_');" class="text" value="<fmt:formatDate dateStyle="full" pattern="dd-MM-yyyy" value="${person.dob}"/>"/>
                            <a href="javascript:void(0);" onclick="displayDatePicker('dob_');"><img src="style/images/calendar.png" alt="calendar" border="0"></a>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td><input type="submit" value="Save"/></td>
                    </tr>
                </table>
            </div>
            </form>
            <br />
            <a href="index.html" class="back">back</a>
        </div>
    </body>
    </html>
  11. Put resources such as css, script and images at Web Pages folder.

There are many workarounds needed to enhance this code such as:

  • No validation. we can use Programmatic validators (e.g. using Validator interface) or Declarative validators (e.g. Commons Validator and VALANG).
  • Using MultiActionController instead of Controller to group a logical set of actions into single controller implementation class.
  • Using annotations to create intuitive and lean code.
  • Using Property Editors instead of tricky setDob_() method to parse from form to pojo.
  • Use i18n for to support different locales.
  • There is no user messages.
  • could you please add??

That’s all for this earlier version. To preview the result please take a look this post at point 10 (as noted earlier, we are going to build similar application). I used netbeans 6.5 to create this simple application. Download Simple CRUD – SpringMVC & Hibernate3. Happy Programming!!

Advertisements

Written by Henri H.

May 25, 2009 at 2:04 pm

Posted in JAVA

37 Responses

Subscribe to comments with RSS.

  1. if you dont mind, please give explanation for every program you wrote..
    biar lebih jelas gitu om..
    Anyway good hen..

    hadi

    May 31, 2009 at 12:55 pm

  2. Cara jalaninnya gimana mas?
    gw kan backgroundnya PHP… kalo di PHP tinggal di taro di htdocs trus access di URL,, kalo ini ?

    imamiscool

    June 16, 2009 at 2:09 pm

  3. @imam
    find steps to run this code (also available at docs folder if you download complete code) at http://code.google.com/p/simple-crud-application/

    Henri H.

    June 16, 2009 at 6:57 pm

  4. Wah hebat bro.. Kalau dilihat dari tulisannya kayaknya udah faham betul nih ama Spring MVC. Bagus codingannya, bersih.

    @imam: cara nge-gunainnya tinggal di export jadi war, trus taroh di folder webapp nya Tomcat. Trus tinggal dijalanin deh Tomcatnya.

    andarasu

    July 14, 2009 at 10:17 pm

  5. Mas, thx bgt artikel nya…nice one,
    tapi boleh dijelasin per step ga….
    karena, itu file nya smua, kita create
    sendiri, atao ad yg auto create dari IDE nya..
    regards,
    deni

    deni

    July 26, 2009 at 2:11 pm

  6. @deni
    coba create web project pake netbeans, pilih spring & hibernate, dari situ bisa diliat file yang digenerate IDE. sisanya kudu dibuat sendiri ๐Ÿ˜€

    Henri H.

    July 26, 2009 at 4:07 pm

  7. there’s a reference to ParameterizableViewController in bean “add.html” but there’s NO this class in the tutorial…

    alex

    March 25, 2010 at 5:42 pm

  8. Also you reference to a variable “test” in index.html but it is not defined…

    …..

    Prev
    ….

    Henri, are you sure this is a working code?!

    alex

    March 25, 2010 at 5:58 pm

  9. to previous post

    alex

    March 25, 2010 at 6:00 pm

  10. @alex
    yes, it is working. my friend (at first comment) already downloaded the code and it’s working.

    ParameterizableViewController is spring class. of course you should find it from spring (include .jar).

    โ€œtestโ€ in index.jsp is not a variable. it is JSTL syntax.

    Henri H.

    March 26, 2010 at 4:40 pm

  11. hi Henri,

    yes, you are right it should be working!

    I figured it out after struggling with epression test=”${object.field==’c’}” if field of type Character the reslt is always true.

    Also ParameterizableViewController was not found stright away in my case.

    everything works fine, thank you Henri, sorry the confusion and my complains.

    Alexey

    Alex

    April 6, 2010 at 3:37 pm

  12. Hi Henri

    great article, it saved me a lot of time, but I’m facing problems in case of many-to-one, one-to-many, or many-to-many associations can you explain how to do crud operations or please give some examples for these cases following the same architecture.

    THANKS

    Haitam

    June 7, 2010 at 12:33 am

  13. i’m always getting this error..

    In-place deployment at C:\Users\user1\Documents\NetBeansProjects\CRUD\build\web
    Initializing…
    deploy?path=C:\Users\user1\Documents\NetBeansProjects\CRUD\build\web&name=CRUD&force=true failed on Personal GlassFish v3 Domain
    C:\Users\user1\Documents\NetBeansProjects\CRUD\nbproject\build-impl.xml:588: The module has not been deployed.
    BUILD FAILED (total time: 18 seconds)

    me

    July 23, 2010 at 8:42 am

  14. is this spring mvc 3?

    me

    July 23, 2010 at 9:59 am

  15. Perfect for Beginners…………. Working Fine………
    Thank u…………..

    Ramakrishnan

    August 4, 2010 at 12:31 pm

  16. can you please help me in putting a validation. i can’t integrate it your .jsp format.

    me.ME.me

    August 24, 2010 at 12:50 pm

  17. Great post! i also wanna share a spoon-fed version of adding CRUD capabilities on Spring MVC using Hibernate JPA.

    http://www.adobocode.com/spring/adding-crud-capability-to-spring-mvc

    tnx

    paul

    November 22, 2010 at 11:07 am

  18. that link too has validations, just try

    paul

    November 22, 2010 at 11:08 am

  19. Tx..

    Its working fine.

    I would include Criteria for login checking for this application.

    Iam unable to create sessionFactory Object. throwing NullPointerException.

    Any body plz solved my prob..

    Is it right code to instatiate sessionFactory in personDAOHib class?

    vamsi

    February 2, 2011 at 6:18 pm

  20. org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘personService’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot create inner bean ‘training.springmvc.crud.service.PersonServiceImpl#a34b91’ of type [training.springmvc.crud.service.PersonServiceImpl] while setting bean property ‘target’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘training.springmvc.crud.service.PersonServiceImpl#a34b91’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean ‘personDAO’ while setting bean property ‘personDAO’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [training.springmvc.crud.dao.PersonDAOHib]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:229)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:117)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1274)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1042)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:485)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:407)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:735)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:369)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:251)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3934)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4429)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:526)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:630)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:514)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1288)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:297)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:857)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:795)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1473)
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:824)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:350)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:196)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Thread.java:636)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘training.springmvc.crud.service.PersonServiceImpl#a34b91’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean ‘personDAO’ while setting bean property ‘personDAO’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [training.springmvc.crud.dao.PersonDAOHib]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:274)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1274)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1042)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:485)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:219)
    … 53 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [training.springmvc.crud.dao.PersonDAOHib]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:917)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:873)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:514)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:485)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:268)
    … 61 more
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [training.springmvc.crud.dao.PersonDAOHib]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:98)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:911)
    … 71 more
    Caused by: java.lang.NullPointerException
    at training.springmvc.crud.dao.PersonDAOHib.(PersonDAOHib.java:37)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:83)
    … 73 more
    2 Feb, 2011 4:48:11 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext

    vamsi

    February 2, 2011 at 6:20 pm

  21. nice spring crud article.

    johnmukkad

    February 24, 2011 at 7:21 pm

  22. Hi this is a nice tutorial.

    can you please tell us what versions of :
    Spring
    Hibernate

    are you using ?

    or if there is a link to download them. ?

    thanks

    Kamal

    April 11, 2011 at 10:49 am

  23. Thank you so much!
    It’s very useful!

    vutuanduc

    August 16, 2011 at 12:06 am

  24. Hey There. I found your weblog the use of msn. That is an extremely smartly written article. I’ll be sure to bookmark it and come back to learn extra of your useful info. Thank you for the post. I will definitely return.

    followers on twitter

    January 9, 2012 at 4:04 pm

  25. As a newbie, I found this very helpful but I have got stuck when I tried to extend the program into sub-directories as I cannot find a way to debug my additional files in NetBeans. I could post the files on this site for your comment but would it be better and quicker if I uploaded them to a file transfer site. This I could do if you send me your email address.

    Robert

    January 15, 2012 at 8:20 pm

  26. Very good example. I am trying to do some similar (With a previous filter to show the list). It works nice but the problem appears when I added a new register and the PageListHolder does not refresh to show the new one.
    Maybe i need to include in the save controller the necesary code to manage the PageListHolder for refreshing with the add function. What do you think?

    Leny

    July 24, 2012 at 6:49 pm

  27. Jan 2, 2013 3:38:43 PM org.springframework.web.context.ContextLoader initWebApplicationContext
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.getDeclaredConstructor(Class.java:1985)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:54)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
    … 24 more
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    … 30 more
    Jan 2, 2013 3:38:43 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Jan 2, 2013 3:38:43 PM org.apache.catalina.core.StandardContext startInternal

    Prafulla

    January 2, 2013 at 5:15 pm

  28. Can any one tell me y this error r coming ?

    Jan 2, 2013 3:38:43 PM org.springframework.web.context.ContextLoader initWebApplicationContext
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.getDeclaredConstructor(Class.java:1985)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:54)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
    … 24 more
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    … 30 more
    Jan 2, 2013 3:38:43 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Jan 2, 2013 3:38:43 PM org.apache.catalina.core.StandardContext startInternal

    Prafulla

    January 2, 2013 at 5:16 pm

  29. I am in fact thankful to the owner of this website
    who has shared this enormous article at here.

    Find Out More

    May 9, 2013 at 9:34 am

  30. We are a bunch of volunteers and opening a brand new scheme in our community.
    Your web site offered us with helpful information to work on.
    You’ve performed a formidable process and our whole community might be thankful to you.

    get more info

    May 12, 2013 at 8:53 am

  31. Interest rates on most of our current needs from photovoltaic film
    energy, especially solar, the outlook for next steps as we look at right now?
    As we have demonstrated in the fourth quarter.

    renewable wealth

    May 25, 2013 at 7:32 am

  32. They seem to be permanent and can be used to make these custom-made engraved fret picks.
    For now, we’ll stick to the pickups.

    Dwayne

    May 29, 2013 at 2:06 pm

  33. Very good post. I will be experiencing some of these issues as
    well..

    New LeBron Shoes

    June 25, 2013 at 5:42 pm

  34. Nike Shox NZ, RO, Classic and Nike Shox R4 are actually only two
    from time honored type Nike Shox in order to see your debt start to dwindle down to nothing.

    Women Nike air max pas cher are attracted by film stars;
    you may be disappointed, for sometimes, those shoes
    in online shops, their Nike shoes are a little tight with Nike shoes on feet.

    Chaussure Air Max Enfant

    August 3, 2013 at 6:45 am

  35. William D May 28, 2013, that michael kors outlet
    ex-LB Michael Boley was secretly copped for child abuse in February 2013.
    All without pay Former Saints defensive coordinator Gregg Williams, ran
    a program from 2009-11 that offered cash payouts for hits that injured opponents.
    Kickoff is scheduled for 8:20 and the game clock in the second half that
    culminated in what they hope will be the second regular-season NFL game
    played outside North America.

    Michael Kors Bags

    August 9, 2013 at 11:32 am

  36. Isn’t it you don’t need to create your own table because Hibernate will take care of this automatically using HBM2DDL?

    grails

    August 13, 2013 at 2:10 pm

  37. keren bang, makasi ya, udah mau ngajarin.. ๐Ÿ™‚

    Adrie Savana

    May 21, 2014 at 9:26 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: