Spring 3 and hibernate integration tutorial with example

This tutorial is focused on usage of Hibernate with Spring 3 framework. I will show that how a basic end to end application flow looks like as a result of this integration.

spring 3 hibernate integration example

Employee management screen

Development environment

For those, who are not using maven for dependency management and are relying on downloaded jar files. I have created another project with all required jar files included in source code to download. Also, I have done integration using Spring 3.2.5 and hibernate 4.
So if you fall into any of above two category, please read below linked post in case any problem.

Spring 3.2.5.RELEASE and Hibernate 4 Integration Example Tutorial with All Jar files

To build this example project, I will guide you step by step. I this way we able to walk through some concepts also.

Step 1) Create a maven web application using below command from command prompt.

mvn archetype:generate -DgroupId=com.howtodoinjava.app -DartifactId=Spring3HibernateIntegration
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Now, convert this web application to ecplise dynamic web project using below commands.

cd Spring3HibernateIntegration
mvn eclipse:eclipse -Dwtpversion=2.0

Step 2) Update pom.xml file to include spring 3 and hibernate dependencies. It will also include mysql driver added in project references. Now again execute command “mvn eclipse:eclipse -Dwtpversion=2.0” to reflect the dependencies in project.

As pom.xml file is too big so I am not writing it here in this post. If you want see the file, please download the project from download link and use it.

Step 3) Now lets decide out database table structure because it will be needed when we will write the entity classes in next step.

CREATE TABLE EMPLOYEE
(
    ID          INT PRIMARY KEY AUTO_INCREMENT,
    FIRSTNAME   VARCHAR(30),
    LASTNAME    VARCHAR(30),
    TELEPHONE   VARCHAR(15),
    EMAIL       VARCHAR(30),
    CREATED     TIMESTAMP DEFAULT NOW()
);

Step 4) Now its time to write EmployeeEntity.java. This class will be mapped to Employee table in database using hibernate. JPA will include any class annotated with @Entity in the persistence management setup. You don’t need persistence.xml if you use annotations.

package com.howtodoinjava.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMPLOYEE")
public class EmployeeEntity {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;

    @Column(name="TELEPHONE")
    private String telephone;

	//Add setters and getters
}

Step 5) Lets write our DAO classes which will be responsible for database interaction. This class will be essentially using the hibernate session factory for database interaction. The session factory implementation will be injected into reference variable at runtime using spring IoC feature.

EmployeeDao.java

package com.howtodoinjava.dao;

import java.util.List;
import com.howtodoinjava.entity.EmployeeEntity;

public interface EmployeeDAO
{
    public void addEmployee(EmployeeEntity employee);
    public List<EmployeeEntity> getAllEmployees();
    public void deleteEmployee(Integer employeeId);
}

EmployeeDaoImpl.java

package com.howtodoinjava.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.howtodoinjava.entity.EmployeeEntity;

@Repository
public class EmployeeDaoImpl implements EmployeeDAO  {

	@Autowired
        private SessionFactory sessionFactory;

	@Override
	public void addEmployee(EmployeeEntity employee) {
		this.sessionFactory.getCurrentSession().save(employee);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EmployeeEntity> getAllEmployees() {
		return this.sessionFactory.getCurrentSession().createQuery("from EmployeeEntity").list();
	}

	@Override
	public void deleteEmployee(Integer employeeId) {
		EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load(
				EmployeeEntity.class, employeeId);
        if (null != employee) {
        	this.sessionFactory.getCurrentSession().delete(employee);
        }
	}
}

Step 5) I have written a manager layer also which seems redundant in this demo due less complexity but it as always considered best practice if you write this. This layer will simply take call from controller and pass this call to dao layer.

EmployeeManager.java

package com.howtodoinjava.service;

import java.util.List;

import com.howtodoinjava.entity.EmployeeEntity;

public interface EmployeeManager {
    public void addEmployee(EmployeeEntity employee);
    public List<EmployeeEntity> getAllEmployees();
    public void deleteEmployee(Integer employeeId);
}

EmployeeManagerImpl.java

package com.howtodoinjava.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.howtodoinjava.dao.EmployeeDAO;
import com.howtodoinjava.entity.EmployeeEntity;

@Service
public class EmployeeManagerImpl implements EmployeeManager {

	@Autowired
        private EmployeeDAO employeeDAO;

	@Override
	@Transactional
	public void addEmployee(EmployeeEntity employee) {
		employeeDAO.addEmployee(employee);
	}

	@Override
	@Transactional
	public List<EmployeeEntity> getAllEmployees() {
		return employeeDAO.getAllEmployees();
	}

	@Override
	@Transactional
	public void deleteEmployee(Integer employeeId) {
		employeeDAO.deleteEmployee(employeeId);
	}

	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}
}

Step 6) Now its time to write the controller which will actually be called from spring framework’s dispatcher servlet to process actual application logic.

EditEmployeeController.java

package com.howtodoinjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.service.EmployeeManager;

@Controller
public class EditEmployeeController {

	@Autowired
	private EmployeeManager employeeManager;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String listEmployees(ModelMap map)
	{
		map.addAttribute("employee", new EmployeeEntity());
		map.addAttribute("employeeList", employeeManager.getAllEmployees());

		return "editEmployeeList";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addEmployee(@ModelAttribute(value="employee") EmployeeEntity employee, BindingResult result)
	{
		employeeManager.addEmployee(employee);
		return "redirect:/";
	}

	@RequestMapping("/delete/{employeeId}")
	public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId)
	{
		employeeManager.deleteEmployee(employeeId);
		return "redirect:/";
	}

	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}
}

Step 7) Now we will write our application’s view layer which is actually a .jsp file.

editEmployeeList.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title>
</head>
<body>
 
<h2>Employee Management Screen : Spring 3 hibernate integration example on www.howtodoinjava.com</h2>
 
<form:form method="post" action="add" commandName="employee">
 
    <table>
    <tr>
        <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="email"><spring:message code="label.email"/></form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="<spring:message code="label.add"/>"/>
        </td>
    </tr>
</table> 
</form:form>
 
     
<h3>Employees</h3>
<c:if  test="${!empty employeeList}">
<table class="data">
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Telephone</th>
    <th>&amp;amp;amp;amp;amp;amp;nbsp;</th>
</tr>
<c:forEach items="${employeeList}" var="emp">
    <tr>
        <td>${emp.lastname}, ${emp.firstname} </td>
        <td>${emp.email}</td>
        <td>${emp.telephone}</td>
        <td><a href="delete/${emp.id}">delete</a></td>
    </tr>
</c:forEach>
</table>
</c:if>
 
</body>
</html>

Step 8) Our java code is complete and now its time to configure the application. Lets start from web.xml. In web.xml, we will configure the front controller for spring framework that is DispatcherServlet.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    
  <display-name>Archetype Created Web Application</display-name>
  	<welcome-file-list>
  		<welcome-file>/WEB-INF/index.jsp</welcome-file>
  	</welcome-file-list>
    <servlet>
        <servlet-name>employee</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>/WEB-INF/employee-servlet.xml</param-value>
	</context-param>
    <listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

Step 9) Lets configure spring framework for hibernate data source, message resources, view resolvers and other such things.

employee-servlet.xml

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.howtodoinjava.controller" />

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties"></bean>

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}"></bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>
    <bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

Step 10) Hibernate configuration becomes simple when using annotation. Lets see how easy it is.

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="com.howtodoinjava.entity.EmployeeEntity"></mapping>
    </session-factory>
</hibernate-configuration>

Step 11) Lets mention jdbc connection properties and message resource properties.

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=password

messages_en.properties

label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.add=Add Employee

label.menu=Actions
label.title=Employee Form
label.footer=www.HowToDoInJava.com

That’s it. Your application is ready to be deployed on server of your choice. At the end, your project structure should look like this.

Spring 3 hibernate integration project structure

Spring 3 hibernate integration project structure

If you find any issue in building or running this application, drop em a comment and I will try to help you.

Update:

If you are facing issue :: “java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider
Possible Solution: Please try changing org.springframework.orm.hibernate3.LocalSessionFactoryBean to org.springframework.orm.hibernate4.LocalSessionFactoryBean
===hibernate3 to hibernate4===

More references:

http://stackoverflow.com/questions/7528862/exception-noclassdeffounderror-for-cacheprovider

http://code.google.com/p/jgk-spring-recipes/wiki/Migrating_Spring31_Hibernate4

java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Possible Solution: Download and add com.springsource.org.aopalliance-1.0.0.jar to your classpath

Refer:

http://forum.spring.io/forum/spring-projects/aop/74011-java-lang-noclassdeffounderror-org-aopalliance-intercept-methodinterceptor

Happy Learning !!

Lokesh has written 269 articles

I have 7 Years of rich experience in java technology. This has only increased my hunger to learn more. In this blog, i will be writing on different topics occasionally, and would love to engage in some meaningful serious discussions with you folks.

187 thoughts on “Spring 3 and hibernate integration tutorial with example

    1. Sandeep says:

      Hi Lokesh, i got good knowledge ..it is very useful for me…. one more thing instead of using sessionFactory we can use Hibernate Template class… we can reduce the code.. i think so no need of separate hibernate configuration file.. we can directly injected to AnnotatedSessionFactory ..

    1. Surendra says:

      Sorry that was behavior of Intellij IDE…after adding hibernate support for the project…that error resolved…Thank you!!! your project successfully run…

  1. Vipin says:

    public List getAllEmployees() {
    return this.sessionFactory.getCurrentSession().createQuery(“from EmployeeEntity”).list();
    }

    this is not working for me ….
    i had almost copied yours example….

      1. Lokesh says:

        Use below code:
        ApplicationContext ac = new ClassPathXmlApplicationContext(“net/core/example/app-context.xml”);

        In maven src/main/java is directory structure and not included in class path. From next time, confirm the path in “classes” folber inside “target” folder.

  2. Vipin says:

    Hi Lokesh….
    i m new to hibernate n facing a problem ….which is how to retrieved a single object from a database…
    and also a list of objects from database…..
    whenever i tried to retrieved a single employee object ..error is…. get or load is not valid without active transaction… i had gooogled a lot but unable to fix this problem…Also
    Can we return a object after retrieving it in service layer from try n catch block..???

    1. Lokesh says:

      Can you please post your hibernate configuration code and code where you are getting this exception. First look suggest that you are opening the transaction after a get/load method call. I.e. load() method is called outside a transaction.

  3. harish says:

    Dear Sir,

    I am getting java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext; error while deleting with the ID.

  4. ganesh says:

    i am getting following exception:-
    java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘employee’ available as request attribute

  5. Siva says:

    Hi Lokesh,

    It’s really good sample to start with Spring and hibernate framework. I’m trying to follow the steps you have described, but i’m getting below warning message while executing the command “mvn eclipse:eclipse -Dwtpversion=2.0″ at step 2:

    [WARNING] Workspace defines a VM that does not contain a valid jre/lib/rt.jar: C:\Program Files\Java\jre7

    What could be the reason for this warning message. Could you please assist me to over come this?

    Thanks,
    Siva

  6. Manisha Pandey says:

    Hello wanna thank you for this amazing tutorial ….I ws successful in this but when I tried this with JSF instead of JSP i am getting exception
    Class ‘org.springframework.faces.webflow.SpringBeanWebFlowVariableResolver’ is missing a runtime dependency: java.lang.NoClassDefFoundError: org/springframework/web/jsf/SpringBeanVariableResolver
    It will be realy kind of you if u culd help me with this and explain the same thing with JSF. Thank you again

    1. Lokesh says:

      Just make sure you got spring web module loaded in runtime:

      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
      </dependency>

  7. Andrew says:

    Sad to say but this tutorial is so messy and waste of time. Missing lots of instructions, I set up totally fresh envirnoment and it generated me lots of erros. Right after importing fresh maven generated files into Eclipse. I do not want to point all the missing things because there is a lot of them but for example author doesnt says how to import project into Eclipse (this step already generated number of errors) Than creation of Java class and its’ location is not mentioned. For me it was just lost of time going through this mess. I would suggest author to test his tutorials on fresh envirnoment not on half configured, that would saved a log of time his readers. I went through few of Lynda.com tutorials and NEVER have any suprising error.

    1. Lokesh says:

      I am very sorry if this tutorial caused so much pain to you. But, believe me I got lots of positive feedback for this tutorial and many people configured it in their first attempt.
      Though, I do not expect anybody to configure all above steps in first attempt because they are complex for many of us. But, even if you are able to execute it in an hour also with 4-5 problems, then also I would say it’s good for you. I call this learning by mistakes. It is much more important than able to execute the project in first attempt.

      Just to mention, I have attached the whole sourcecode (which is 100% correctly configured and executable) for reference if somebody struck for long time.

  8. velmurugan says:

    Hi Lokesh,

    I am getting below error.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class [ com.howtodoinjava.entity.EmployeeEntity] declared in Hibernate configuration entry
    .
    .
    .
    Caused by: org.hibernate.MappingException: Unable to load class [ com.howtodoinjava.entity.EmployeeEntity] declared in Hibernate configuration entry
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2126)

    Please suggest me, what i need to change the code.

  9. Venkata Sriram says:

    Hi sir.i used the same code to delete an employee,but in my case iam having extenstion in web.xml as *.vja so when i use delete it is not going to controller sir. in controller also same code i followed as explained in the tutorial.please Help me sir.

    Thanks
    Venkata Sriram

  10. sarojineveen says:

    i am facing this error can you please help me.

    WARNING: No mapping found for HTTP request with URI [/SpringwithORM/] in DispatcherServlet with name ‘employee’
    Jan 17, 2014 4:11:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound

  11. nadhine says:

    hello! thanks for the tutorial. I would like to know one thing … within your project has other things … login, logout, access denied, but the project goes only to “Employee Management” screen is ok? Or missing something here? If not how can I implement this elsewhere?

    Sorry for my english GTranslate

  12. Mike says:

    Lokesh,

    I followed your tutorial and used the same design except I wanted to use Volleyball recruits instead of Employees so I had…

    Volleyball (instead of Spring3HibernateIntegration)

    Recruit (instead of EmployeeEntity)
    RecruitDAO (instead of EmployeeDAO)
    RecruitDAOImpl (instead of EmployeeDAOImpl)

    so forth and so on….and I changed all the references accordingly in all the files.

    Also, I am using Tomcat instead of JBoss.

    However I keep getting this error when I try to launch the program inside of STS. (Yes I’m also using Spring Tool Suite).

    Jan 06, 2014 9:48:13 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/volleyball/] in DispatcherServlet with name ‘recruit’

    I will gladly post the code if you request so.

    Thanks and thanks for the excellent tutorial.

    Mike

    1. When you start the tomcat, you will see the server logs in console like below:

      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Root mapping to handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/add] onto handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/add.*] onto handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/add/] onto handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/delete/{employeeId}] onto handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/delete/{employeeId}.*] onto handler 'editEmployeeController'
      Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
      INFO: Mapped URL path [/delete/{employeeId}/] onto handler 'editEmployeeController'

      See if your URL is scanned and registered.

      1. Mike says:

        Lokesh,

        Here is the text from the console. I don’t think the SLF4J error is the problem and I think the URL (http://localhost:8080/volleyball) is registered but I’m not certain.

        SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
        SLF4J: Defaulting to no-operation (NOP) logger implementation
        SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
        [INFO] Scanning for projects…
        [WARNING]
        [WARNING] Some problems were encountered while building the effective model for volleyball.dao:volleyball:war:0.0.1-SNAPSHOT
        [WARNING] ‘dependencies.dependency.(groupId:artifactId:type:classifier)’ must be unique: org.hibernate:hibernate-core:jar -> duplicate declaration of version ${hibernate.version} @ line 78, column 15
        [WARNING]
        [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
        [WARNING]
        [WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
        [WARNING]
        [INFO]
        [INFO] ————————————————————————
        [INFO] Building volleyball 0.0.1-SNAPSHOT
        [INFO] ————————————————————————
        [INFO]
        [INFO] — maven-clean-plugin:2.4.1:clean (default-clean) @ volleyball —
        [INFO] Deleting C:springworkspacevolleyballtarget
        [INFO]
        [INFO] — maven-resources-plugin:2.5:resources (default-resources) @ volleyball —
        [debug] execute contextualize
        [INFO] Using ‘UTF-8′ encoding to copy filtered resources.
        [INFO] Copying 5 resources
        [INFO]
        [INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ volleyball —
        [INFO] Compiling 6 source files to C:springworkspacevolleyballtargetclasses
        [INFO]
        [INFO] — maven-resources-plugin:2.5:testResources (default-testResources) @ volleyball —
        [debug] execute contextualize
        [INFO] Using ‘UTF-8′ encoding to copy filtered resources.
        [INFO] skip non existing resourceDirectory C:springworkspacevolleyballsrctestresources
        [INFO]
        [INFO] — maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ volleyball —
        [INFO] Nothing to compile – all classes are up to date
        [INFO]
        [INFO] — maven-surefire-plugin:2.10:test (default-test) @ volleyball —
        [INFO] No tests to run.
        [INFO] Surefire report directory: C:springworkspacevolleyballtargetsurefire-reports

        ——————————————————-
        T E S T S
        ——————————————————-

        Results :

        Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

        [INFO]
        [INFO] — maven-war-plugin:2.1.1:war (default-war) @ volleyball —
        [INFO] Packaging webapp
        [INFO] Assembling webapp [volleyball] in [C:springworkspacevolleyballtargetvolleyball-0.0.1-SNAPSHOT]
        [INFO] Processing war project
        [INFO] Copying webapp resources [C:springworkspacevolleyballsrcmainwebapp]
        [INFO] Webapp assembled in [689 msecs]
        [INFO] Building war: C:springworkspacevolleyballtargetvolleyball-0.0.1-SNAPSHOT.war
        [WARNING] Warning: selected war files include a WEB-INF/web.xml which will be ignored
        (webxml attribute is missing from war task, or ignoreWebxml attribute is specified as ‘true’)
        [INFO]
        [INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) @ volleyball >>>
        [INFO]
        [INFO] — maven-resources-plugin:2.5:resources (default-resources) @ volleyball —
        [debug] execute contextualize
        [INFO] Using ‘UTF-8′ encoding to copy filtered resources.
        [INFO] Copying 5 resources
        [INFO]
        [INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ volleyball —
        [INFO] Nothing to compile – all classes are up to date
        [INFO]
        [INFO] < << tomcat7-maven-plugin:2.2:run (default-cli) @ volleyball <<<
        [INFO]
        [INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ volleyball ---
        [INFO] Running war on http://localhost:8080/volleyball
        [INFO] Creating Tomcat server configuration at C:springworkspacevolleyballtargettomcat
        [INFO] create webapp with contextPath: /volleyball
        Jan 07, 2014 4:23:07 PM org.apache.coyote.AbstractProtocol init
        INFO: Initializing ProtocolHandler ["http-bio-8080"]
        Jan 07, 2014 4:23:07 PM org.apache.catalina.core.StandardService startInternal
        INFO: Starting service Tomcat
        Jan 07, 2014 4:23:07 PM org.apache.catalina.core.StandardEngine startInternal
        INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
        Jan 07, 2014 4:23:16 PM org.apache.catalina.core.ApplicationContext log
        INFO: No Spring WebApplicationInitializer types detected on classpath
        Jan 07, 2014 4:23:17 PM org.apache.catalina.core.ApplicationContext log
        INFO: Initializing Spring root WebApplicationContext
        Jan 07, 2014 4:23:17 PM org.springframework.web.context.ContextLoader initWebApplicationContext
        INFO: Root WebApplicationContext: initialization started
        Jan 07, 2014 4:23:17 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
        INFO: Refreshing Root WebApplicationContext: startup date [Tue Jan 07 16:23:17 EST 2014]; root of context hierarchy
        Jan 07, 2014 4:23:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
        INFO: Loading XML bean definitions from class path resource [spring/application-config.xml]
        Jan 07, 2014 4:23:17 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
        INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@52970046: defining beans []; root of factory hierarchy
        Jan 07, 2014 4:23:17 PM org.springframework.web.context.ContextLoader initWebApplicationContext
        INFO: Root WebApplicationContext: initialization completed in 763 ms
        Jan 07, 2014 4:23:17 PM org.apache.catalina.core.ApplicationContext log
        INFO: Initializing Spring FrameworkServlet 'recruit'
        Jan 07, 2014 4:23:17 PM org.springframework.web.servlet.FrameworkServlet initServletBean
        INFO: FrameworkServlet 'recruit': initialization started
        Jan 07, 2014 4:23:17 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
        INFO: Refreshing WebApplicationContext for namespace 'recruit-servlet': startup date [Tue Jan 07 16:23:17 EST 2014]; parent: Root WebApplicationContext
        Jan 07, 2014 4:23:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
        INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-config.xml]
        Jan 07, 2014 4:23:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
        INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3c2fd5b: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@52970046
        Jan 07, 2014 4:23:19 PM org.springframework.web.servlet.FrameworkServlet initServletBean
        INFO: FrameworkServlet 'recruit': initialization completed in 1421 ms
        Jan 07, 2014 4:23:19 PM org.apache.coyote.AbstractProtocol start
        INFO: Starting ProtocolHandler ["http-bio-8080"]

            1. Finally I looked on this application. I didn’t find any problem with code. I believe problem is with program structure because when I used the same code and dependency in separate project, code worked fine. Below are steps I followed:
              1) Create new maven project: [I renamed the project to vollyballs]
              D:Latest Setupeclipse_juno_workspacevollyballs>mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=vollyballs
              -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

              2) Concert to eclipse supported project
              cd vollyballs

              mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0
              3) Import project into eclipse and copy files from your code
              4) Execute command: mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0 to update dependencies
              5) Deploy the app in tomcat server. Application was good and running.

              I have uploaded the working code here:
              https://drive.google.com/file/d/0B7yo2HclmjI4YTlVUkpSZ1YwS1k/edit?usp=sharing

  13. Venkata Sriram says:

    Hi sir, iam newbie to spring.Iam having a doubt related to beans sir.i read your tutorial regarding Autowired and it types.and practiced the spring hibernate integration example.

    i want to call a method in the same bean then how i have to call sir.

    like

    public class XX
    {
    public String AA()
    {

    //Here i want to call BB() with out using new method is it possible sir ?

    }

    public String BB()
    {

    }

    }

    public class YY

    {
    @Autowired
    private XX x;
    then
    x.AA();// will work sir
    x.BB();//working
    }

    but in the same bean how to call iam confusing please help me sir

          1. Hi lokesh, could you help me regarding how to manage transaction in spring with hibernate, i used annonation @transactional on service method. but i want to use manually
            Session session = sessionFactory.getCurrentSession();
            TransactionManager tx = null;
            try {
            tx= session.beginTransaction();
            …..
            ..
            ..
            tx.commit();
            } catch (Exception e) {
            tx.rollback();
            }

            but it doesn’t working.
            so please tell me how to use?
            your site is good but how to post new thread or blog here..
            thanks

            1. What’s problem you are facing in above code? AND, I will recommend you to use annotations for controlling transactions. It is more manageable and reduce lots of code. I am planning to add a forum in this blog, so that problems like this can be discussed in detail there.

  14. Sebastian says:

    Hello, can you help with this error?
    SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4149)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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:601)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

      1. Sebastian says:

        Can you tell me how to do that? I’ve just started studying this. I must mention that I use STS(Spring Tools Suite) and I created a Dynamic Web Project from the beginning. Thank you.

  15. helios says:

    Could you please help me a problem.
    When i start Tomcat, occur an error. Although, I used the springweb jar in the library.

    SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

  16. Andros says:

    Hello!!
    I have this problem. when I run the example it appears in my web browser a 404.in both jsp (index and edit…)
    the web project its exactly as yours. This is the jars that I have in the lib

    com.springsource.org.aopalliance-1.0.0.jar
    commons-dbcp-1.4.jar
    commons-logging.jar
    hibernate-core-3.6.3.Final.jar
    jstl-1.2.jar
    mysql-connector-java-5.1.27.jar
    org.springframework.web.servlet-3.0.0.M3.jar
    spring-aop-3.0.3.RELEASE.jar
    spring-asm-3.0.3.RELEASE.jar
    spring-beans-3.0.3.RELEASE.jar
    spring-context-3.0.3.RELEASE.jar
    spring-core-3.0.3.RELEASE.jar
    spring-expression-3.0.3.RELEASE.jar
    spring-tx-3.0.3.RELEASE.jar
    spring-web-3.0.3.RELEASE.jar
    spring-webmvc-3.0.3.RELEASE.jar

    And I really need your help here. I know that the problem is in the web.xml but where???
    thanks

  17. A M Bharath says:

    Hello Lokesh,

    A general question regarding the concept of DAO layer…I assume the DAO interface represents a blueprint of various CRUD operations that can be performed on a Datasource (any datasource in fact) and each DAOImpl class refers to a specific Datasource (like MySQLDaoImpl, MongoDBDaoImpl etc) right? If this is the case, how to fit in some operational semantics that vastly differ from one Datasource to the another for the same kind of operation?

    Eg:

    public Object save(Object obj) -> let us say this applies to an insert operation using Hibernate for a MySQL datasource
    public void save(Entity entity) -> let us say this applies to the same operation (insert) using some other JPA-based ORM for a NoSQL-type datasource like Cassandra/MongoDB

    Please note that Entity, in the aforementioned, is the JPA-standard Annotation type.

    In this case, how do we go about designing the interface and/or implementation classes of the DAO layer?

    Sincerely,
    A M Bharath

    1. Bharath, It is a good question. My understanding is that we should not use Entity or any such class extensions out of DAO layer. We should use VO (Value objects) or TEO (Transfer Entity Object) which have almost similar fields/getters,setters/structure as Entity.

      These VOs however can be used as model at view layer. And they will be present at controller and service layer, but not at DAO layer.
      e.g. public EmployeeVO save(EmployeeVO employee);

      Above declaration will completely de-couple the DAO layer from service layer because it does not care what you do in DAOImpl with EmployeeVO object, It just want that employee information saved somehow. Similarly other DAO methods will not accept/return any entity type thing. They will return only void/common java types or VO objects. They just need to copy the values from VO objects to DB specific objects and use them afterward. Similarily, after fetching data, they need to copy information in VO objects and return it.

      In future, if you want to move from from hibernate to MongoDB, you will have to change only DAOImpl classes.

      Am I missing anything???

      1. A M Bharath says:

        Perfect! :) I now understand what it means to truly decouple the DAO layer from the others…you cleared my question to the fullest! Thanks!!

        Sincerely,
        A M Bharath

        1. Ravi Kumar says:

          If i click on delete it is not deleting that row .In console “Hibernate: select registeren0_.id as id2_, registeren0_.NAME as NAME2_ from RegisterEntity registeren0” my application is same as above.How to solve it ?

  18. prasanta says:

    Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeManager’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.dao.EmployeeDAO com.howtodoinjava.service.EmployeeManagerImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeDAO’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.jdbc.datasource.DataSourceUtils.doCloseConnection(Ljava/sql/Connection;Ljavax/sql/DataSource;)V

  19. Dinesh says:

    I am doing small application is same as above,every thing is working but if i click on delete it is not deleting that row .In console “Hibernate: select registeren0_.id as id2_, registeren0_.NAME as NAME2_ from RegisterEntity registeren0_”
    ..where i did mistake can you help me for this.

  20. Dilli says:

    How to solve this ?
    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

  21. Tyrone says:

    Hi Lokesh

    Please assist, I have downloaded the source code and imported into Eclipse. I’ve made relevant changes to jdbc.properties

    I want to do it step by step once I am sure that the project is running on my machine.

    When I run the project I get Http status 404 – The requested resource (/Spring3HibernateIntegration/) is not available.

    Please help, what am I missing. I’m new to Spring3MVC

  22. Hi,

    help me to solve this issue …

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.LocalSessionFactoryBean] for bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.LocalSessionFactoryBean
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)

  23. Could not autowire field: private org.hibernate.SessionFactory com.aj.dao.EmployeeDaoImpl.sessionFactory; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
    ms

  24. Das Kumar says:

    While doing one application i am getting this error:
    java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘register’ available as request attribute
    ..How to solve this error can you help me

      1. Das Kumar says:

        not required action ?.I am doing small application same as above application.In the above application you did’t write like .htm in request mapping.May i know what is the exact problem.

          1. Das Kumar says:

            That id only.And one more thing is edit link i have to write there .if i click edit link one small window should come and there i want to edit.if it is possible please share sir.

  25. Bharath says:

    Hi Lokesh,

    In the EMPLOYEE table, there is a column, “CREATED TIMESTAMP DEFAULT NOW()” but the EmployeeEntity class doesn’t seem to have a property representing this. Can you please explain how this column is getting updated upon the execution of the addEmployee(…) method?

    Also, I’ve seen some posts in StackOverflow where there are recommendations to use JPA annotations like @PrePersist, @PostPersist etc to update TIMESTAMP columns (like CREATED, LAST_UPDATED etc). It has also been mentioned that Hibernate doesn’t support these annotations by default and that some listeners have to be used. Do you have any inputs in this regard?

    1. I have used “DEFAULT NOW()” in DB schema for table which causes to store current timestamp everytime a new record is added.

      @PrePersist, @PostPersist are new to me. I will learn more on them, and share my views.

      1. A M Bharath says:

        Hello Lokesh,

        Thanks for your reply – in effect, you wrote the timestamp logic in your DB itself! Good idea there!

        I was looking up some information on @PrePersist and @PostPersist etc. These are pure-JPA annotations and can’t be used with Hibernate’s SessionFactory. The work-around is to use either an interceptor (http://java.dzone.com/articles/using-a-hibernate-interceptor-) OR an event-listener (http://leakfromjavaheap.blogspot.in/2013/08/prepersist-and-preupdate-not-working.html & http://timezra.blogspot.in/2011/10/jpa-callbacks-with-hibernate.html)

        Do have a look at these since I’m sure these will make better sense to you than the newbie in me! :)

        Thanks,
        A M Bharath

      2. A M Bharath says:

        Hello Lokesh,

        Another question on the same lines:

        - If there has to be another database column called “updated” [that represents the last "updated" time stamp - i.e., when an update query is executed in the DAO layer for an "edit employee information" functionality in the application], how would you achieve it?

        Thanks,
        A M Bharath

  26. sats says:

    Hello, Lokesh Gupta.
    I’m doing everything written above step-by-step.
    when trying to run the project I get:

    log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
    log4j:WARN Please initialize the log4j system properly.
    окт 17, 2013 2:04:09 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    окт 17, 2013 2:04:09 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [] startup failed due to previous errors
    [2013-10-17 02:04:09,503] Artifact Employee:war exploded: Error during artifact deployment. See server log for details.

    What can I be doing wrong?
    I’m using Intellij Idea 12, Tomcat 7

  27. yogesh gandhi says:

    after adding the aop jar (from spring 3.0.2 dependencies), i was getting a class not found error in tomcat logs.

    To Fix that I had to change the BasicDataSource class, that is mentioned in employee-servlet.xml

    Correct class w.r.t. tomcat = org.apache.tomcat.dbcp.dbcp.BasicDataSource

    While earlier it was

    Cannot find class [org.apache.commons.dbcp.BasicDataSource

  28. Akansh Bhatnagar says:

    Hi Lokesh, I am trying to run above code by I am getting below exception:

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/employee-servlet.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

    Please help in this.

  29. John says:

    Thanks Lokesh for the comments. I have resolved the above issue ..Currently facing another issue after resolving it. I am putting the stracktrace below. Can you pls tell me is it because of version mismatch of the jars. I am not sure about the error. Just a guess… Please find the stracktrace

    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeManager’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.dao.EmployeeDAO com.howtodoinjava.service.EmployeeManagerImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeDAO’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/annotations/common/AssertionFailure
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
    at org.a

  30. Andrew says:

    I tried to deploy the above application in Tomcat and getting the foloowing error. Please find the stracktrace below.. Any help will be appreciated..

    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.howtodoinjava.dao.EmployeeDaoImpl] for bean with name ‘employeeDAO’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.howtodoinjava.dao.EmployeeDaoImpl
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at or

    1. Andrew, I tried many times but unable to replicate this issue. You see, for many others, it worked perfectly fine. So there must be something you are doing differently. Can you please list down the steps.

      FYI, I did this:
      1) Downloaded the project in eclipse workspace
      2) Run prompt > mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0
      3) Deploy the application on server
      4) Access the URL: http://localhost:8080/Spring3HibernateIntegration/

      Note: Make sure you have created the “employee” table in “test” DB

      1. Idrees says:


        java.lang.NullPointerException
        com.tpc.money.dao.AuthenticationDAOImpl.getUser(AuthenticationDAOImpl.java:34)
        com.tpc.money.service.auth.AuthenticateUser.authenticate(AuthenticateUser.java:44)
        com.tpc.money.service.filter.AuthFilter.validate(AuthFilter.java:65)
        com.tpc.money.service.filter.AuthFilter.filter(AuthFilter.java:54)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1454)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
        note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.

        application-context.xml

        org.hibernate.dialect.MySQLDialect
        true

        com.tpc.money.hibernate.Employee
        com.tpc.money.hibernate.AppUsers
        com.tpc.money.hibernate.Account
        com.tpc.money.hibernate.TPCTransaction

        WRITE_DATES_AS_TIMESTAMPS

          1. Idrees says:

            Hmm.. Ok this application is using Jersey spring and hibernate.. It is working using hibernate.cfg.xml using hibernateutils class, I want to convert that using session factory from application-context and inject that in DAOs.

            and I am getting null pointer… I will see if I can put the code or provide download link.

            Thanks for your replies!

  31. Gowtham says:

    Hi! I imported the entire project in eclipse. But in editEmployeeList.jsp the following ‘Can not find the tag library descriptor for “http://www.springframework.org/tags” ‘ for . Can you explain me how to resolve this……

  32. keda87 says:

    i’ve tried this tutorial with netbeans without maven and tomcat as server. and file structure it was same as on this tutorial. but i got an error like this :

    SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
    java.lang.IllegalStateException: BeanFactory not initialized or already closed – call ‘refresh’ before accessing beans via the ApplicationContext

  33. Anandan Rajendran says:

    Hi,
    I am using JBoss5.1. when i run the application i am getting the following error.

    10:42:49,242 INFO [Version] Hibernate Commons Annotations 3.1.0.GA
    10:42:49,274 INFO [STDOUT] 10:42:49,274 INFO [DefaultListableBeanFactory] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@72e235: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,editEmployeeController,jspViewResolver,messageSource,propertyConfigurer,dataSource,sessionFactory,employeeDAO,employeeManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
    10:42:49,331 INFO [STDOUT] 10:42:49,316 ERROR [ContextLoader] Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeManager’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.dao.EmployeeDAO com.howtodoinjava.service.EmployeeManagerImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘employeeDAO’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)

    1. java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist

      Clearly file is not found where it is expected. Try to resolve this file path issue.

      Also, verify the file in classes folder.

  34. sudhindra says:

    hi i am getting error like this:
    type Exception report

    message

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Neither BindingResult nor plain target object for bean name ‘employee’ available as request attribute
    root cause

    javax.servlet.jsp.JspTagException: Neither BindingResult nor plain target object for bean name ‘employee’ available as request attribute
    note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.

    what to do..?

  35. Pradeep says:

    I tried out this sample and it works great. However I have some doubts to solve my specific issue:
    1. In the EmployeeDTO object has a object like Address which is say a different class, how do we create the
    form since the form contains only one commandName.
    2. Second, Can we make the controller class accept json request also. How?

    Please let me know the solutions for the above two. Your help is greaty appriciated.

    Regards,
    Pradeep

    1. 1) You can pass HashMap to view. In this way, you can send multiple different objects (not associated together) within single command object.

      Another way is to wrap all data in a class, let’s say, EmployeeAddressVO and set all data in this class and pass to view layer.

      2) Absolutely. Use headers=”Accept=application/json;” is request mapping. A working example with XML: http://howtodoinjava.com/2012/12/15/how-to-write-restful-webservices-using-spring-3-mvc/

      1. Pradeep says:

        I am planning to go with the first approach. Regarding your first reply: How can I populate the hashmap object and send it to the view? Also how to access the hashmap inside the jsp. Could you please eloborate?

  36. sudhindra says:

    run:
    Aug 20, 2013 10:46:34 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@20985fa2: startup date [Tue Aug 20 22:46:34 IST 2013]; root of context hierarchy
    Aug 20, 2013 10:46:34 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@10c767b1: defining beans []; root of factory hierarchy
    Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘userManagerImpl’ is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
    at test.LoginTest.main(LoginTest.java:10)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    i am using netbeans ide….pls help..

      1. sudhindra says:

        this is the code ,where i am getting error………

        package service;

        import java.util.List;
        import model.Person;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

        public class TestSpringHibernateDaoSupport {

        public static void main(String[] args) {
        System.out.println(“************** BEGINNING PROGRAM **************”);

        ApplicationContext context = new ClassPathXmlApplicationContext(“**/dispatcher-servlet.xml”);
        PersonService personService = (PersonService) context.getBean(“personService”);

        Person person = new Person();
        person.setName(“Alba”);
        person.setEmail(“alba@gmail.com”);
        person.setId(“alba”);
        personService.addPerson(person);
        System.out.println(“Person : ” + person + ” added successfully”);

        List persons = personService.fetchAllPersons();
        System.out.println(“The list of all persons = ” + persons);

        System.out.println(“************** ENDING PROGRAM *****************”);
        }
        }

        error:

        run:
        ************** BEGINNING PROGRAM **************
        Aug 24, 2013 4:35:24 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
        INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@326d234c: startup date [Sat Aug 24 16:35:24 IST 2013]; root of context hierarchy
        Aug 24, 2013 4:35:24 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
        INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14b3b898: defining beans []; root of factory hierarchy
        Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘personService’ is defined
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
        at service.TestSpringHibernateDaoSupport.main(TestSpringHibernateDaoSupport.java:14)
        Java Result: 1
        BUILD SUCCESSFUL (total time: 8 seconds)

        its a spring hibernate integration program

  37. kehinde says:

    Thanks. Though been new to the Spring world I think I have not gained my hands around some thing. Please can you prepare a war file of this so that I can just deploy it directly? Possibly it may the way I’m handling it that made me not get it. a war file for a beginner like me will be a very good start. Thanks.

  38. deepak singh says:

    hi lokesh,
    thanks a lot for the fantastic tutorial. good work.
    I am facing a small issue.
    ${emp.firstname} and other data is not appearing on jsp.
    though in the controller I could see the value of List..
    do you have clue??

  39. thanks for sharing. I have learned that is possible to redirect to the same page using return “redirect:/”; but i have a question, if you are redirecting to / over any invocation controller methods, you are creating a new EmployeeEntity() and inserting over the map, even if it is not necessary, dont you think? Please share with us what you think.

    otherwise, forgive my poor english, i am spaniard.

  40. ken4ward says:

    Thank you, Gupta. I have been on this for a while and it seems I am not yet getting somethings right because anytime I try to run the code, it generates this in the log file and it show 404 error, what should I do? Thanks.

    Aug 14, 2013 2:46:14 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:Program FilesJavajdk1.7.0_17bin;C:WindowsSunJavabin;C:Windowssystem32;C:Windows;C:UsersKen4wardDesktopLatest CyclosCloudBeescloudbees-sdk-1.5.0;C:Program FilesJavajdk1.7.0_17bin;C:apache-maven-3.0.5bin;C:Program FilesMicrosoftWeb Platform Installer;C:Program Files (x86)Windows Kits8.1Windows Performance Toolkit;C:Program FilesMicrosoft SQL Server110ToolsBinn;C:Ruby200-x64bin;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:Program Files (x86)Gitcmd;C:Ruby200-x64bin;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;.
    Aug 14, 2013 2:46:16 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Spring3HibernateIntegration’ did not find a matching property.
    Aug 14, 2013 2:46:18 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8585"]
    Aug 14, 2013 2:46:19 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8099"]
    Aug 14, 2013 2:46:19 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 4910 ms
    Aug 14, 2013 2:46:19 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    Aug 14, 2013 2:46:19 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.30
    Aug 14, 2013 2:46:20 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
    INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [280] milliseconds.
    Aug 14, 2013 2:46:27 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    Aug 14, 2013 2:46:27 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    Aug 14, 2013 2:46:28 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    java.lang.NoClassDefFoundError: org/springframework/expression/PropertyAccessor
    at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:553)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.ClassNotFoundException: org.springframework.expression.PropertyAccessor
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    … 15 more

    Aug 14, 2013 2:46:28 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Aug 14, 2013 2:46:28 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/Spring3HibernateIntegration] startup failed due to previous errors
    Aug 14, 2013 2:46:28 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    Aug 14, 2013 2:46:28 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8585"]
    Aug 14, 2013 2:46:28 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8099"]
    Aug 14, 2013 2:46:28 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 9763 ms

      1. ken4ward says:

        I downloaded the source code but implemented it on my own, not importing the code into Eclipse.
        1. I downloaded the source code.
        2. Created a web application project in Eclipse with the same name.
        3. Created the application structure as it is indicated here.
        4. Opened the pom.xml file and manually added the dependencies into the lib folder of the app.
        5. Went to app Build path, go to the directory of the project and copied all the dependencies into the path as external jars.
        6. Created files and just copy and pasted the codes from the forum here. Everything compiled fine, only the employee-servlet.xml flags a warning that javax.servlet is not found.
        7. Deployed the application to Tomcat7.
        Please I do not want to use Maven, it create a new learning curve for me, just want to try it out with webapps. The response is :”404 error”. Please help. Thanks.

        1. I will suggest you to import first the downloaded sourcecode in some other application (with different name) and add all JAR dependencies you are using in existing project. Try to make it work first.

          Once this application is successfully deployed and running, then you move code piece by piece into your new project.

      1. siddharth says:

        where file? where download? i cant find these two… please explain from a-z how to download these application in a single shot ..
        Thanks ,
        Siddharth

  41. dharmendra says:

    I reached this blog searching for annotation based Spring 3 and Hibernate 4 application in the hope that I will get rid of the xml configurations. But sadly this was not what I was looking for. Moreover, no where I found any tutorial for the same. Hence I wrote one. Putting a link here to benefit the users who might come here for what I was looking for.

    http://techieme.in/techieme/xml-free-spring-hibernate-configuration/

    To the admin: Please feel free to delete my comment and link if you think it to be offending.

      1. anil says:

        and 1 more thing i want to bring to ur notice is the records are not storing in db. when we restart the server the records which are inserted previously is not in db at all…. can u tell me whats the solution for it. as i need to write junit test cases the records has to be in db otherwise it will not pass.

          1. anil says:

            ya its working fine now…i tried as u mentioned u above. prior to that i made an entry in employee-servlet.xml. as true even after autocommiting the records are not storing in db.. and at last i made a post to u.. thanks for ur advise

        1. narendra says:

          i am getting the below error while i run the application.
          SEVERE: Servlet.service() for servlet employee threw exception
          java.sql.SQLException: ORA-02289: sequence does not exist

          at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
          at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
          at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:213)

Want to ask any question? Or suggest anything?