HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Spring hibernate integration example

By Lokesh Gupta | Filed Under: Spring ORM

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

1. Development environment

  • Eclipse Juno IDE
  • JDK 1.7
  • JBoss 7
  • Maven
  • Spring 3.0.5
  • Hibernate 3.6.3
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 + Hibernate 4 integration tutorial with all jar files

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

2. Create maven web project

Create a maven web project 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 project to ecplise dynamic web project using below maven command.

$ cd Spring3HibernateIntegration
$ mvn eclipse:eclipse -Dwtpversion=2.0

3. Maven dependecies

Update pom.xml file to include spring and hibernate dependencies. It will also include mysql driver added in project references.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava.app</groupId>
  <artifactId>Spring3HibernateIntegration</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Spring3HibernateIntegration Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!-- JBoss repository for Hibernate -->
	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
		</repository>
	</repositories>
  <properties>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
  </properties>
  <dependencies>

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

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

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

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

	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-context-support</artifactId>
	  <version>${org.springframework.version}</version>
	</dependency>
	 
	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-jdbc</artifactId>
	  <version>${org.springframework.version}</version>
	</dependency>

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

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

	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-webmvc</artifactId>
	  <version>${org.springframework.version}</version>
	</dependency>
	
	<dependency>  
       <groupId>log4j</groupId>  
       <artifactId>log4j</artifactId>  
       <version>1.2.15</version>  
       <scope>runtime</scope>  
     </dependency>  
     
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-core</artifactId>
		<version>3.6.3.Final</version>
	</dependency>

	<dependency>
		<groupId>javassist</groupId>
		<artifactId>javassist</artifactId>
		<version>3.12.1.GA</version>
	</dependency>
 
 	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
		<scope>runtime</scope>
	</dependency>
	
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
		<scope>runtime</scope>
	</dependency>
	
	<dependency>
	  <groupId>commons-dbcp</groupId>
	  <artifactId>commons-dbcp</artifactId>
	  <version>1.4</version>
	</dependency>
        
   <dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.9</version>
	</dependency>
	
  </dependencies>
  <build>
    <finalName>Spring3HibernateIntegration</finalName>
  </build>
</project>

4. Create database schema

Now lets decide out database schema 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()
);

5. Write hibernate entity classes

Now its time to write EmployeeEntity. 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;

    //Setters and getters
}

6. Write data access code

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.

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);
}
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);
        }
    }
}

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.

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);
}
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;
    }
}

7. Spring controller and view files

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

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;
    }
}

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

<%@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>Action</th>
    </tr>
    <c:forEach items="${employeeList}" var="emp">
        <tr>
            <td>${emp.lastname}, ${emp.firstname} </td>
            <td>${emp.email}</td>
            <td>${emp.telephone}</td>
            <td>delete</td>
        </tr>
    </c:forEach>
    </table>
    </c:if>
    </body>
</html>

8. Spring dispatcher servlet

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.

<?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>

9. Spring hibernate integration configuration

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

<?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>

Hibernate configuration becomes simple when using annotation.

<?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>

10. JDBC Properties

Lets mention jdbc connection properties and message resource 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
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 + hibernate integration project structure

If you find any issue in building or running this spring hibernate integration example in eclipse step by step, drop em a comment and I will try to help you.

Download source code

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
https://code.google.com/archive/p/jgk-spring-recipes/wikis/Migrating_Spring31_Hibernate4.wiki


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

Download source code

Happy Learning !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. arun singh

    June 6, 2018

    Thanks sir

    Reply
  2. saravanan

    March 31, 2018

    cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘context:annotation-config’.

    Reply
  3. OSMAN

    December 25, 2016

    hello,
    i need a JPA exemple to improve my quality

    the Spring hibernate exemple is a good exemple for me that i thnak you

    best regards

    Reply
  4. Selven

    December 20, 2016

    Hi,
    I am facing this error when I run spring and hibernate integration in eclipse:

    SEVERE: Context initialization failed
    org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 19 in XML document from ServletContext resource [/WEB-INF/employee-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 112; cvc-elt.1: Cannot find the declaration of element 'beans'.
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    
    Reply
    • Lokesh Gupta

      December 21, 2016

      Check for namespace declaration. xmlns=”http://www.springframework.org/schema/beans
      xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

      Reply
  5. m

    April 13, 2016

    hi, could you show an example of integrating jsf, spring and hibernate? Thank you

    Reply
    • Lokesh Gupta

      April 13, 2016

      Added in my TODO list.

      Reply
  6. Davis

    April 7, 2016

    Hi Lokesh,
    I created a project in Eclipse Luna. I picked jboss-javaee6-webapp-ear-archtype. I dropped the sample code in the respective folders.Project builds with out errors. But I am getting following errors.

    Initialization of bean failed; nested exception is java.lang.ClassCastException: org.springframework.transaction.annotation.Propagation cannot be cast to org.springframework.transaction.annotation.Propagation

    Reply
    • Lokesh Gupta

      April 7, 2016

      Never heard of this error. I will try to find a solution for it. As of now, I have no clue.

      Reply
      • Davis

        April 9, 2016

        Is there any way I can send a screen shot of my project structure ?
        My best guess is, it is due to following keywords in spring-servlet.xml.

        Reply
        • Lokesh Gupta

          April 9, 2016

          Send me at howtodoinjava@gmail.com

          Reply
          • Davis Alengaden

            May 16, 2016

            Hi Lokesh,
            I could fix the issue. As I had picked jboss-javaee6-webapp-ear-archtype ,
            there were three projects in the project structure – ear, ejb and war. Each project has its own porm and one main porm. I had same porm entries in multiple pom.xml which caused the issue. I removed redundant entries and dropped your project in appropriate folders in sync with archtype…. everything works fine now.
            Thank you
            Davis

            Reply
  7. ss..

    January 24, 2016

    Hi i am not able to import this project..

    Reply
  8. shweta

    December 11, 2015

    Getting exception in spring maven project–Servlet /Emp threw load() exception.
    I have added all the dependencies in pom.xml.

    Reply
  9. rohit

    December 8, 2015

    getting this exception when running the application on jboss 7.1.

    17:30:22,334 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."Spring3HibernateIntegration.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."Spring3HibernateIntegration.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "Spring3HibernateIntegration.war"
    	at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.0.Final.jar:7.1.0.Final]
    	at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_65]
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_65]
    	at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_65]
    Caused by: java.lang.RuntimeException: Error getting reflective information for class org.springframework.web.servlet.DispatcherServlet with ClassLoader ModuleClassLoader for Module "deployment.Spring3HibernateIntegration.war:main" from Service Module Loader
    	at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:70) [jboss-as-server-7.1.0.Final.jar:7.1.0.Final]
    	at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotationInformation(MethodAnnotationAggregator.java:58)
    	at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.handleAnnotations(InterceptorAnnotationProcessor.java:70)
    	at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig(InterceptorAnnotationProcessor.java:117)
    	at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy(InterceptorAnnotationProcessor.java:54)
    	at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.0.Final.jar:7.1.0.Final]
    	... 5 more
    Caused by: java.lang.NoClassDefFoundError: org/springframework/web/context/WebApplicationContext
    	at java.lang.Class.getDeclaredFields0(Native Method) [rt.jar:1.7.0_65]
    	at java.lang.Class.privateGetDeclaredFields(Class.java:2436) [rt.jar:1.7.0_65]
    	at java.lang.Class.getDeclaredFields(Class.java:1806) [rt.jar:1.7.0_65]
    	at org.jboss.as.server.deployment.reflect.ClassReflectionIndex.(ClassReflectionIndex.java:57) [jboss-as-server-7.1.0.Final.jar:7.1.0.Final]
    	at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:66) [jboss-as-server-7.1.0.Final.jar:7.1.0.Final]
    	... 10 more
    Caused by: java.lang.ClassNotFoundException: org.springframework.web.context.WebApplicationContext from [Module "deployment.Spring3HibernateIntegration.war:main" from Service Module Loader]
    	at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    	at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
    	... 15 more
    
    17:30:22,379 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "Spring3HibernateIntegration.war" was rolled back with failure message {"JBAS014671: Failed services" =&gt; {"jboss.deployment.unit.\"Spring3HibernateIntegration.war\".POST_MODULE" =&gt; "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"Spring3HibernateIntegration.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"Spring3HibernateIntegration.war\""}}
    17:30:22,485 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015877: Stopped deployment Spring3HibernateIntegration.war in 105ms
    17:30:22,518 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
    JBAS014777:   Services which failed to start:      service jboss.deployment.unit."Spring3HibernateIntegration.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."Spring3HibernateIntegration.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "Spring3HibernateIntegration.war"
    
    17:30:22,524 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" =&gt; {"Operation step-2" =&gt; {"JBAS014671: Failed services" =&gt; {"jboss.deployment.unit.\"Spring3HibernateIntegration.war\".POST_MODULE" =&gt; "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"Spring3HibernateIntegration.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"Spring3HibernateIntegration.war\""}}}}
    Reply
  10. Amarjeet kumar

    June 29, 2015

    Hi Lokesh….
    I have go through this code ….it is very easy to Understand the concept of Spring Hibernate Integration But….when I choose add maven project option and i have seen in my Project Explorer ….Some error like:—

    “The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path”

    Reply
    • Danish

      November 5, 2015

      Project->Properties->Target Runtimes->Apache Tomcat

      Reply
  11. Tsuisou

    March 11, 2015

    I have this problem when I try to run the project. SB help me?

    HTTP Status 500 – javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code ‘label.firstname’ for locale ‘pl’.

    type Exception report

    message javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code 'label.firstname' for locale 'pl'.
    
    description The server encountered an internal error that prevented it from fulfilling this request.
    
    exception
    
    org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code 'label.firstname' for locale 'pl'.
    	org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:548)
    	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:454)
    	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    	org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    	org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    	org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    
    root cause
    
    javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code 'label.firstname' for locale 'pl'.
    	org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:908)
    	org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:837)
    	org.apache.jsp.WEB_002dINF.view.editEmployeeList_jsp._jspService(editEmployeeList_jsp.java:151)
    	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:431)
    	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    	org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    	org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    	org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    
    root cause
    
    javax.servlet.jsp.JspTagException: No message found under code 'label.firstname' for locale 'pl'.
    	org.springframework.web.servlet.tags.MessageTag.doStartTagInternal(MessageTag.java:184)
    	org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    	org.apache.jsp.WEB_002dINF.view.editEmployeeList_jsp._jspx_meth_spring_005fmessage_005f0(editEmployeeList_jsp.java:297)
    	org.apache.jsp.WEB_002dINF.view.editEmployeeList_jsp._jspx_meth_form_005flabel_005f0(editEmployeeList_jsp.java:264)
    	org.apache.jsp.WEB_002dINF.view.editEmployeeList_jsp._jspx_meth_form_005fform_005f0(editEmployeeList_jsp.java:183)
    	org.apache.jsp.WEB_002dINF.view.editEmployeeList_jsp._jspService(editEmployeeList_jsp.java:128)
    	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:431)
    	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    	org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    	org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    	org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    note The full stack trace of the root cause is available in the Apache Tomcat/8.0.20 logs.
    Apache Tomcat/8.0.20

    Reply
    • Lokesh

      March 16, 2015

      Create a file messages_pl.properties with content of messages_en.properties (you can translate the values as well) in resources folder.

      Reply
  12. Ricardo

    February 19, 2015

    Hello!
    How could I make a simple and efficient way to handle exceptions returned from my oracle database through the spring? Would use the DataAccessException? Thank you!!

    Reply
    • Lokesh

      February 20, 2015

      Personally, I am not big fan of DataAccessException. I usually like to have more control over exceptions using @ExceptionHandler approach.

      If you are looking to translate oracle exception codes directly then YES, DataAccessException is good way. If you are more concerned about handling exceptions, then try second approach.

      Reply
      • Ricardo

        February 20, 2015

        I am not able to intercept the exception. He goes straight. Already put in catch ConstraintViolationException, Exception and DataAccessException but does not work. Would have any examples of how you did?

        Following error:

        fev 20, 2015 11:06:37 AM org.hibernate.util.JDBCExceptionReporter logExceptions
        ADVERTÊNCIA: SQL Error: 1, SQLState: 23000
        fev 20, 2015 11:06:37 AM org.hibernate.util.JDBCExceptionReporter logExceptions
        GRAVE: ORA-00001: unique constraint (REDEATMPC.IPK_TPMEIOACESSOPROTOCOLO) violated
        
        fev 20, 2015 11:06:37 AM org.hibernate.util.JDBCExceptionReporter logExceptions
        ADVERTÊNCIA: SQL Error: 1, SQLState: 23000
        fev 20, 2015 11:06:37 AM org.hibernate.util.JDBCExceptionReporter logExceptions
        GRAVE: ORA-00001: unique constraint (REDEATMPC.IPK_TPMEIOACESSOPROTOCOLO) violated
        
        fev 20, 2015 11:06:37 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
        GRAVE: Could not synchronize database state with session
        org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        	at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
        	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
        	at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
        	at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
        	at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        	at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
        	at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
        	at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
        	at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:657)
        Reply
        • Lokesh

          February 21, 2015

          This thread will help you if you not gone through it already. TODO: Catch the exception outside transaction boundary. This exception is not thrown by spring managed bean. Rather hibernate’s transactionmanager is throwing it from some proxy object.

          Reply
  13. Badal

    February 6, 2015

    Getting below error. Please help!!!

    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    java.lang.NoSuchMethodError: org.springframework.beans.factory.annotation.InjectionMetadata.(Ljava/lang/Class;)V
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:350)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:798)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:493)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    	at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:710)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410)
    	at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
    	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.run(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    Reply
    • Lokesh

      February 6, 2015

      Please use latest spring jars; and remove any older versions if any.

      Reply
  14. Iniya

    December 18, 2014

    I tried both your below examples. Both are opening white blank page in the browser. Log files in tomcat is given below. I have been working on this for few days now. Please help me.

    https://howtodoinjava.com/spring-orm/spring-hibernate-integration-example/
    https://howtodoinjava.com/struts-2/spring-4-struts-2-hibernate-integration-tutorial/

    http://localhost:8081/Spring3HibernateIntegration/index.jsp
    http://localhost:8081/Spring3HibernateIntegration/editEmployeeList.jsp
    http://localhost:8081/Spring3HibernateIntegration/

    localhost_access_log.2014-12-18.txt

    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:00:46 -0500] “GET /Spring3HibernateIntegration/ HTTP/1.1” 404 –
    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:51 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:55 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:56 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:57 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
    0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:06:11 -0500] “GET /Spring3HibernateIntegration/ HTTP/1.1” 404 –

    Reply
    • Lokesh

      December 18, 2014

      “GET /Spring3HibernateIntegration/ HTTP/1.1″ 404

      Something bad happened during deployment i.e. startup time in tomcat. Please check server logs. Are there any error while startup?

      Reply
  15. prem

    November 24, 2014

    Consider there are multiple requests. Since same instance of the servlet runs and Spring bean (EmployeeManager) isnot thread safe..How Spring bean thread-safety is taken care.

    @Autowired
    private EmployeeManager employeeManager;

    Reply
    • Lokesh

      November 24, 2014

      Above variable (and other similar data as well) is not stateful data. Except initialization, no thread will ever change/modify it. Usually Manager and DAO layer classes never store any stateful data which is changed by any thread. And until you have any stateful data which can possibly be corrupted, never worry about multi-threading issue.

      Reply
      • prem

        November 30, 2014

        Thanks, got it now.

        Reply
  16. Umashankar

    November 15, 2014

    SEVERE: Context initialization failed

    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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    	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:4701)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
    	at java.util.concurrent.FutureTask.run(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: 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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    	... 20 more
    Caused by: 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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
    	... 22 more
    Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException
    	at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
    	at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
    	at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
    	at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
    	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
    	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
    	at org.hibernate.cfg.Configuration.(Configuration.java:151)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    	at java.lang.reflect.Constructor.newInstance(Unknown Source)
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
    	at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:821)
    	at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:552)
    	at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    	... 32 more
    Caused by: java.lang.ClassNotFoundException: ch.qos.logback.core.joran.spi.JoranException
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    	... 50 more
    
    Nov 15, 2014 10:37:11 PM org.apache.catalina.core.StandardContext listenerStart
    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 '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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    	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:4701)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
    	at java.util.concurrent.FutureTask.run(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: 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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    	... 20 more
    Caused by: 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: ch/qos/logback/core/joran/spi/JoranException
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
    	... 22 more
    Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException
    	at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
    	at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
    	at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
    	at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
    	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
    	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
    	at org.hibernate.cfg.Configuration.(Configuration.java:151)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    	at java.lang.reflect.Constructor.newInstance(Unknown Source)
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
    	at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:821)
    	at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:552)
    	at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    	... 32 more
    Caused by: java.lang.ClassNotFoundException: ch.qos.logback.core.joran.spi.JoranException
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    	... 50 more
    
    Nov 15, 2014 10:37:11 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Nov 15, 2014 10:37:11 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/Spring3HibernateIntegration] startup failed due to previous errors
    Nov 15, 2014 10:37:11 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    Nov 15, 2014 10:37:11 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
    SEVERE: The web application [/Spring3HibernateIntegration] registered the JDBC driver [org.postgresql.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
    Nov 15, 2014 10:37:11 PM org.apache.coyote.AbstractProtocolHandler start
    INFO: Starting ProtocolHandler ["http-bio-8080"]
    Nov 15, 2014 10:37:11 PM org.apache.coyote.AbstractProtocolHandler start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Nov 15, 2014 10:37:11 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1757 ms
    

    Hi,

    I am getting above error while trying to run the application in eclipse. Have added all necessary jars.

    Please help where i am going wrong in this..

    Reply
    • Lokesh

      November 16, 2014

      “java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException” says all. Logback dependency is missing..

      Reply
      • vinayak

        April 6, 2015

        Check once your .jar file in the WEB-INF/lib foloder..

        Reply
  17. Abhijeet

    October 13, 2014

    HI Lokesh very nice explanation and helpful though.

    I have question: when you return a list of Employee Entity you are returning it from singleton employeeManager as you are not Specifying any scope to it, but while the list changes how does it ensure that the singleton returns the new list every time a a request is made as singleton objects only constructed once .

    Thanks in advance !!!

    Reply
    • Lokesh

      October 13, 2014

      Singleton pattern should only be concern when object is stateful. Stateless objects do not need to be singleton in applications (usually). You will read good information here: https://howtodoinjava.com/for-fun-only/a-birds-eye-view-on-how-web-servers-work/

      Reply
      • Abhijeet

        October 13, 2014

        Hi Lokesh, I meant to say what if the Employee Entity returns a Prototype Bean what if the list changes frequently. and how that would be handled if its constructed as Signleton Bean

        Reply
        • Lokesh

          October 13, 2014

          EmployeeEntity as well as list of entities, is created always by hibernate and totally depends on number of rows obtained as result of query executed. Spring does not create either List of entities, or single entity. And Hibernate always create a new instance of list after query execution.

          I hope I understood your concern right, this time 🙁 . Please let me know if I am still not able to clear your doubt.

          Reply
          • Abhijeet

            October 13, 2014

            Yes that answers my question how does it works in case of Springs leave alone the Hibernate just Spring i wanted to know how can be a prototype bean may always give new value when its a dependency in an Singleton Bean … means when you try get a singleton bean when it has a prototype bean added as dependency

            Reply
            • Lokesh

              October 13, 2014

              “Lookup Method injection” is there exactly for this purpose. See a good example here: https://prasanthnath.wordpress.com/2013/03/21/injecting-a-prototype-bean-into-a-singleton-bean/

              Reply
              • Abhijeet

                October 14, 2014

                Thanks Lokesh for all you explanations this is simply amazing and thanks a lot for helping me 🙂

                Reply
  18. padobPaul

    October 12, 2014

    Thank You for great example of integration. It’s one of the best sources of knowledge in this topic as far I’ve found.
    Good luck and

    Reply
  19. manikandan

    October 11, 2014

    Hi. i am new for Spring and Hibernate, i can’t able to download relevant jar file on it, ll u pls help me.

    Reply
    • Lokesh

      October 12, 2014

      Download from here: https://howtodoinjava.com/spring/spring-orm/spring-3-2-5-release-and-hibernate-4-integration-example-tutorial/

      Reply
  20. vinay

    September 22, 2014

    how can we handle multiple controller in our code ?

    Reply
    • Lokesh

      September 22, 2014

      You can have multiple classes annotated with @Controller. Is it something else you are seeking?

      Reply
  21. JEYASEKAR

    September 18, 2014

    [ERROR] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Compilation failure
    
    C:\WORKSPACE OTERS\Spring_hiber\Spring3HibernateIntegration \src\main\java\com\howtodoinjava\dao\ EmployeeDaoImpl.java:[11,1] annotations are not s
    upported in -source 1.3
    (use -source 5 or higher to enable annotations)
    @Repository
    

    where/what i need to change?
    Am using java 1.6.

    Reply
    • Lokesh

      September 19, 2014

      Don’t know the root cause but adding this to pom.xml should solve the issue.

      <build>
          <pluginManagement>
               <plugins>
                   <plugin>
                       <artifactId>maven-compiler-plugin</artifactId>
                       <version>2.3.2</version>
                       <configuration>
                           <source>1.6</source>
                           <target>1.6</target>
                           <compilerArgument></compilerArgument>
                       </configuration>
                   </plugin>
               </plugins>
          </pluginManagement>
      </build>
      
      Reply
  22. Doreen

    September 18, 2014

    Hi thanks for this tutorial,

    i met with this error, you do know whats causing the issue?

    HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

    Reply
    • Lokesh

      September 18, 2014

      Connection can not be opened. Please verify your db credentials.

      Reply
      • Doreen

        September 18, 2014

        i’ve tried googling about the error, and made changes in the jdbc.properties as well as employee-servlet.xml but it still doesnt works. any idea?

        Reply
  23. Dinesh

    September 11, 2014

    Thanks for your tutorial.

    I’m the beginning of spring and hibernate. I want to learn the basic of spring and hibernate. Can you tell me which is a helpful tutorial (Which you are written) or books to learn the spring and hibernate basic concepts?

    I only know the core Java concept.

    Thanks in Advance.

    Reply
  24. Srikanth

    August 25, 2014

    Hi Lokesh, I’ve tried your code,but getting that Entity class given in mapping tag of hibernate.cfg.xml is not loading …causes hibernate mapping exception…. .might be am in wrong way…could you please help me out… thanks in advance…

    Reply
  25. Ambet

    August 14, 2014

    Thank you Mr. Lokesh, Nice blog for beginners! I was just wondering what do you use in wordpress to post the code blocks?

    Reply
    • Lokesh

      August 14, 2014

      Plugin name is SyntaxHighlighter Evolved

      Reply
  26. Venky

    July 22, 2014

    Good job Mr. Lokesh, Also please post one sample application on Struts 1.x, Spring and Hibernate Integration in real time level.

    Reply
    • Lokesh

      July 22, 2014

      May be it will help you. It is using struts 2 in tutorial, but you can easily replace the pieces from specific to struts 2 to struts 1.

      https://howtodoinjava.com/struts-2/spring-4-struts-2-hibernate-integration-tutorial/

      Reply
      • Venky

        July 23, 2014

        Thanks for your post, Mr Lokesh, I will let you know if i need any clarifications.

        Reply
  27. Aina G

    July 21, 2014

    Hi Mr Lokesh, thank you for your tutorial it helps me to understand Maven
    But i have error when i compile; i used your code 100% without changed anything
    I use netbeans not Eclipse and i have this error
    [/java]
    Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: 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 java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;[/java]

    Best regards
    Aina

    Reply
    • Lokesh

      July 21, 2014

      Have you tried the solution I suggested in last of post in first red block.

      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

      Reply
      • Aina G

        July 22, 2014

        Hi Mr Lokesh,
        Thank you for responding so quickly, i did it and i have two errors:
        First error is :

        spring - property 'configurationClass' is not writable or has an invalid setter method. Does the parameter type of the setter 
        
        I removed      
         and add        
        
        now the error disappear and another error appear:
        
        Grave:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: 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: org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

        can you give me your e-mail? I would like to improve my knowledge in java and I need help to make it happen1!

        Best regards
        Aina G

        Reply
      • Aina G

        July 22, 2014

        Hi, Mr Lokesh, I did as you said to me, the error disappears but an another appears.

        This is the error:
        Invalid property ‘sessionFactory’ of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property ‘sessionFactory’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

        Can i have your e-mail, I would like to improve my knowledge in java and I need help to make it happen.!!

        Best regards,
        Aina G

        Reply
  28. amarnath

    July 20, 2014

    First of all Thanks for the wonderful tutorial. I have successfully integrated Hibernate with Spring following your tutorial.
    But I have one problem, I have included one more DTO that is UserDTO and mapped to USER table in my MYSQL and I have included it in the hibernate.cfg.xml file like below,

    The problem is, it is working fine for the FeedbackDTO but for the UserDTO I am getting an exception as below,
    HouseController:64 – ERROR: HouseController.verifyCredentials USER is not mapped [FROM USER]

    I am unable to figure out, so please let me know how can I solve this.

    Reply
    • Lokesh

      July 20, 2014

      Looks like posted code was lost. Please post the code in tags as suggested above comment box.

      Reply
    • amarnath

      July 20, 2014

      I am able to solve it .. I made a mistake in the Query.
      Query query = session.createQuery(“FROM User”); // Here I am using Db-table name instead of that I have to use the DTO name which I have mapped with the DB-Table;
      Query query = session.createQuery(“FROM UserDTO”);

      Reply
      • Lokesh

        July 20, 2014

        This is the best thing happened. I really like when somebody solves his problem in his own way.

        Reply
  29. ravi

    June 17, 2014

    hi lokesh
    am getting
    org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.StackOverflowError
    this error and am not using maven dependency
    solution
    ….

    Reply
    • Lokesh

      June 17, 2014

      It may happen if your hibernate entities refer to each other such that they create a loop. Check for relationships between hibernate entities.

      Reply
  30. Wilfredo G.

    June 3, 2014

    Hi Lokesh, How can I get contact with you. I have a project that I need some help with. It is a Spring Hibernate project.

    Thanks
    Wilfredo

    Reply
    • Lokesh

      June 3, 2014

      Howtodoinjava@gmail.com

      Reply
  31. Lilliana

    May 13, 2014

    Hi, i did the first steps but when i imported the project i received this error:

    Faceted Project Problem (Java Version Mismatch)

    How i can do to solve this problem?

    Reply
    • Lokesh

      May 14, 2014

      Define the minimum and max JDK version in last of pom.xml like this.

      <build>
          <finalName>name</finalName>
          <plugins>
      		<plugin>
      			<artifactId>maven-compiler-plugin</artifactId>
      			<version>2.3.2</version>
      			<configuration>
      				<source>1.6</source>
      				<target>1.6</target>
      			</configuration>
      		</plugin>
      	</plugins>
        </build>
      
      Reply
  32. anil

    May 1, 2014

    hi Lokesh, need to know few things i want project structure in maven like src/main/java, src/test/java, src/test/resources which archtype i need to use? give me the detailed explanation how to create this type of project structure

    Reply
    • Lokesh

      May 1, 2014

      You should be using maven-archetype-webapp or maven-archetype-quickstart, depends on nature of java project i.e. webapp or normal java app.
      More info is listed here:

      https://maven.apache.org/archetypes/maven-archetype-quickstart/
      https://maven.apache.org/plugins-archives/maven-archetype-plugin-1.0-alpha-7/examples/webapp.html

      Reply
      • ravindhar

        May 12, 2014

        Hi lokesh actually the spring with hibernate directory structure is zig zag i will more elaborate means that musch of complexity having not understand easily understanding

        Reply
        • Lokesh

          May 12, 2014

          Having hard time in understanding the comment.. 🙁

          Reply
    • anil

      May 4, 2014

      did it by integrating with maven-plugin lokesh….can u post the same example by using Jquery…i want to know how it can be integrated….

      Reply
  33. Binh Tran

    April 25, 2014

    Hi Lockesh,

    Would it be best if we don’t mix Spring DI with Hibernate in DAO layer? so we can have total separation between Data and Service Layers?.
    1. Remove Hibernate related Configuration from Spring Bean and put them on backend Data layer
    2. Only Use EmployeeDAO in Spring Bean configuration and AutoWire to EmployeeManager (service layer)

    Please Advice.
    Thanks Binh.

    Reply
    • Lokesh

      April 26, 2014

      Hi Binh, Can you please elaborate more on “Remove Hibernate related Configuration from Spring Bean and put them on backend Data layer”? What exactly you want to do and it’s benefits?

      Reply
      • Binh Tran

        April 29, 2014

        Hi Lokesh,
        What I meant is to decouple Hibernate from Spring. The benefit is to remove coupling and having separation of layers. Please let me know if it is a good idea?

        Thanks.

        Reply
        • Lokesh

          April 29, 2014

          Decoupling in any form is always welcome in my view. Here I really have to think hard of a good way to decouple hibernate from spring completely. I will do my research. If you got any good suggestion, the please share it with all.

          Reply
  34. prem

    April 24, 2014

    Hi lokesh,nice Example..but how to do validations for the fields i.e when they don’t enter any fields.

    Reply
  35. riya

    April 4, 2014

    Hi Lokesh, I have few queries in integration of spring and hibernate. I need your email id. Please reply back to this message.

    Reply
    • Sandeep

      April 23, 2014

      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 ..

      Reply
      • Lokesh

        April 23, 2014

        Good Points. May be I should write another post with above suggestions.

        Reply
  36. bernard

    April 3, 2014

    Thank-you so much for the work done

    Reply
  37. Mohan

    March 27, 2014

    Hi Lokesh,

    index.jsp (welcomefile) is not calling here.could you clarify it?why is it ignoring here?

    Reply
  38. Surendra

    March 24, 2014

    public List getAllEmployees() {
    return this.sessionFactory.getCurrentSession().createQuery(“from EmployeeEntity”).list();
    }
    EmployeeEntity created well and used for , but there is compile time error say “EmployeeEntity” can’t resolved the symbol….
    see also in stackoverflow https://stackoverflow.com/questions/22606636/spring-hibernate-sql-entity-name-not-resolved

    Reply
    • Surendra

      March 25, 2014

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

      Reply
      • Lokesh

        March 25, 2014

        Glad, you resolved it.

        Reply
  39. Vipin

    March 18, 2014

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

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

    Reply
    • Lokesh

      March 18, 2014

      What’s the problem you are facing. Any exception?

      Reply
      • Lokesh

        March 19, 2014

        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.

        Reply
  40. Vipin

    March 18, 2014

    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..???

    Reply
    • Lokesh

      March 18, 2014

      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.

      Reply
  41. harish

    March 18, 2014

    Dear Sir,

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

    Reply
  42. Praveen

    March 10, 2014

    Thanks for providing working model to get started with.

    Reply
  43. ganesh

    March 5, 2014

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

    Reply
    • raja

      April 2, 2014

      try it one more time

      Reply
  44. Binh Thanh Nguyen

    March 4, 2014

    Thanks, nice post.

    Reply
  45. Prashanth

    February 28, 2014

    what are the jar files i need ti include in lib directory if i build the project from source without using maven..

    Reply
    • Lokesh

      February 28, 2014

      You can refer here: https://howtodoinjava.com/spring/spring-orm/spring-3-2-5-release-and-hibernate-4-integration-example-tutorial/

      Reply
  46. Siva

    February 26, 2014

    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

    Reply
  47. Vijay

    February 26, 2014

    Hi Lokesh! This article was very helpful.Thank you so much!!!!!!! Day by day I am becoming your fan!!!!!!

    Reply
  48. Manisha Pandey

    February 22, 2014

    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

    Reply
    • Lokesh

      February 22, 2014

      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>

      Reply
  49. kalyan

    February 16, 2014

    really useful …thank u so much 🙂

    Reply
  50. Piyush Grover

    February 15, 2014

    Thanks Lokesh sir. Awesome post.

    Reply
  51. Andrew

    February 4, 2014

    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.

    Reply
    • Lokesh

      February 4, 2014

      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.

      Reply
  52. velmurugan

    February 4, 2014

    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.

    Reply
    • Lokesh

      February 4, 2014

      Please make you have .class file generated in required pacakge. com/howtodoinjava/entity/EmployeeEntity

      Reply
  53. Roushan

    January 26, 2014

    thanks Sir u r doing a very helpful work.

    Reply
  54. Venkata Sriram

    January 22, 2014

    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

    Reply
    • Venkata Sriram

      January 24, 2014

      Hi sir please help me sir.

      Reply
      • Lokesh

        January 24, 2014

        Can you please zip the source code and upload to google docs and send me link. If zipped folder is small, send it directly to my mail id. howtodoinjava@gmail.com

        Reply
  55. sarojineveen

    January 17, 2014

    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

    Reply
  56. nadhine

    January 8, 2014

    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

    Reply
    • Lokesh Gupta

      January 10, 2014

      It’s how it has been written. If you want to forward any other screen you can do so.

      Reply
  57. Mike

    January 6, 2014

    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

    Reply
    • Lokesh Gupta

      January 7, 2014

      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.

      Reply
      • Mike

        January 8, 2014

        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 &quot;org.slf4j.impl.StaticLoggerBinder&quot;.
        SLF4J: Defaulting to no-operation (NOP) logger implementation
        SLF4J: See https://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 -&gt; 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] &gt;&gt;&gt; tomcat7-maven-plugin:2.2:run (default-cli) @ volleyball &gt;&gt;&gt;
        [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] &lt;&lt;&lt; tomcat7-maven-plugin:2.2:run (default-cli) @ volleyball &lt;&lt;&lt;
        [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 [&quot;http-bio-8080&quot;]
        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 &amp;#039;recruit&amp;#039;
        Jan 07, 2014 4:23:17 PM org.springframework.web.servlet.FrameworkServlet initServletBean
        INFO: FrameworkServlet &amp;#039;recruit&amp;#039;: initialization started
        Jan 07, 2014 4:23:17 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
        INFO: Refreshing WebApplicationContext for namespace &amp;#039;recruit-servlet&amp;#039;: 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 &amp;#039;recruit&amp;#039;: initialization completed in 1421 ms
        Jan 07, 2014 4:23:19 PM org.apache.coyote.AbstractProtocol start
        INFO: Starting ProtocolHandler [&quot;http-bio-8080&quot;]
        Reply
        • Lokesh Gupta

          January 10, 2014

          If it is small project, can you please ip the source and upload it go google docs. And send me link on howtodoinjava@gmail.com

          Reply
          • Mike

            January 10, 2014

            Lokesh,

            Check your email.

            Thanks
            Mike

            Reply
            • Lokesh Gupta

              January 10, 2014

              Got your email. I will reply you on sunday coz I am on vacations and with limited resources here.

              Reply
          • Mike

            January 11, 2014

            Lokesh,

            Enjoy your Vacation. This can wait.

            Mike 🙂

            Reply
            • Lokesh Gupta

              January 12, 2014

              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

              Reply
  58. Venkata Sriram

    January 2, 2014

    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

    Reply
    • Lokesh Gupta

      January 2, 2014

      Not sure what exactly you are looking for? Which method call you want to make in which class in your code sample?

      Reply
      • Venkata Sriram

        January 3, 2014

        Hi sir,i want to call method BB() from AA() sir.

        Reply
        • Lokesh Gupta

          January 3, 2014

          For calling methods defined in same class, you don’t need to do anything. Basic java rule. Call it directly. OR I am not getting you properly?

          Reply
          • Venkata Sriram

            January 3, 2014

            ok sir .Thanks for clarification sir.

            Reply
          • rajeshboy44

            January 6, 2014

            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

            Reply
            • Lokesh Gupta

              January 7, 2014

              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.

              Reply
  59. Dilip

    December 20, 2013

    Its working fine , gr8 .. test .Thanks

    Reply
  60. amit

    December 11, 2013

    good work you have done man.
    Thanks alot!!!

    Reply
  61. Sebastian

    December 9, 2013

    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)
    Reply
    • Lokesh Gupta

      December 9, 2013

      Spring web is not included in dependencies.

      Reply
      • Sebastian

        December 10, 2013

        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.

        Reply
  62. helios

    November 28, 2013

    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)
    Reply
    • helios

      November 29, 2013

      Thanks, I solved this problem.

      Reply
      • Lokesh Gupta

        November 29, 2013

        🙂

        Reply
      • Ola

        December 23, 2013

        how to solved this problem?

        Reply
  63. Andros

    November 24, 2013

    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

    Reply
    • Lokesh Gupta

      November 24, 2013

      Any problem seen in server logs?

      Reply
      • Alex

        December 7, 2013

        I have the same problem, the same jars and in the server logs. are in white
        nothing

        Reply
  64. A M Bharath

    November 20, 2013

    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

    Reply
    • Lokesh Gupta

      November 20, 2013

      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???

      Reply
      • A M Bharath

        November 21, 2013

        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

        Reply
  65. Akram

    November 19, 2013

    Thank you Gupta,
    I imported this tutorial in my STS it’s working, did you forget to implement the update ?
    Thanks

    Reply
    • Ravi Kumar

      December 4, 2013

      How to update ? can you share that.?

      Reply
      • Lokesh Gupta

        December 4, 2013

        Add another method updateEmployee() and it’s code. By the way, it’s not main discussion in post. Post is about integration with Spring 3. I will appreciate If you try first.

        Reply
        • Ravi Kumar

          December 4, 2013

          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 ?

          Reply
          • Ravi Kumar

            December 6, 2013

            I added methods for update and edit also.Two things are done.
            Thank you Gupta.

            Reply
  66. prasanta

    November 18, 2013

    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
    Reply
  67. santhosh

    November 8, 2013

    Hi lokesh,
    Please can you guide dwr integration with same application???
    thanks in advance..

    Reply
  68. santhosh

    November 8, 2013

    Hi,
    for same example can you guide us how to integrate with dwr (ajax)????

    Reply
    • Lokesh Gupta

      November 8, 2013

      Currently on vacations. I will try.

      Reply
  69. Dinesh

    November 7, 2013

    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.

    Reply
  70. Dilli

    November 7, 2013

    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)
    Reply
    • Lokesh Gupta

      November 7, 2013

      Paste your hibernate config here.

      Reply
  71. Tyrone

    October 29, 2013

    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

    Reply
    • Lokesh Gupta

      October 29, 2013

      Please ensure you have all .class files and .xml files in target folder (i.e. project is build correctly). If still facing issue, give the error logs in server console.

      Reply
  72. Ajay Shilwant

    October 28, 2013

    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)
    Reply
    • Lokesh Gupta

      October 28, 2013

      I updated the post just few minutes before. Look at the end (near sourcecode link) for possible solution.

      Reply
  73. Ajay Shilwant

    October 28, 2013

    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
    Reply
    • Lokesh Gupta

      October 28, 2013

      https://stackoverflow.com/questions/8565051/spring-3-1-hibernate-4-sessionfactory
      https://code.google.com/archive/p/jgk-spring-recipes/wikis/Migrating_Spring31_Hibernate4.wiki

      Reply
  74. Das Kumar

    October 27, 2013

    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

    Reply
    • Lokesh Gupta

      October 27, 2013

      The root caused is the incorrect view name in JSP page.
      @RequestMapping(“/customer.htm”)

      Reply
      • Das Kumar

        October 28, 2013

        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.

        Reply
        • Lokesh Gupta

          October 28, 2013

          It’s not about extension. They are for example only. Please verify “commandName” property and related things.

          Reply
          • Das Kumar

            November 5, 2013

            how to edit particular id details..can you please write that code.please help me

            Reply
  75. Das Kumar

    October 21, 2013

    After downloading and extract .To run this project which files are required to paste in eclipse,but not in maveen project.how to do it ?

    Reply
    • Lokesh Gupta

      October 21, 2013

      Add all required jar files. They are in .classpath file in attached sourcecode.

      Reply
      • Das Kumar

        October 22, 2013

        Thank you, it is working. I am new to spring MVC,Shall i write 3 or more controllers in one package ?

        Reply
        • Lokesh Gupta

          October 22, 2013

          If you can logically group them, and group them in package also.

          Reply
      • Das Kumar

        October 22, 2013

        I want to display id,how to get id from data base .can you please send to my mail.

        Reply
        • Lokesh Gupta

          October 23, 2013

          You have the id field in entity. You can use that. Is there any other id you are looking for?

          Reply
          • Das Kumar

            October 23, 2013

            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.

            Reply
  76. Sandeep Tyagi

    October 18, 2013

    Hi Lokesh,

    May you please post your POM file also in this blog, because of security reason i am not able to down load project source code?

    Reply
    • Lokesh Gupta

      October 18, 2013

      check your email.

      Reply
  77. Arun Kumar

    October 17, 2013

    Hi Lokesh,

    Thank you, whenever I am getting confused about any java related concept, I read your concept and always resolve my doubts.

    Thank lots.

    Reply
  78. Bharath

    October 17, 2013

    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?

    Reply
    • Lokesh Gupta

      October 17, 2013

      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.

      Reply
      • A M Bharath

        October 21, 2013

        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 https://dzone.com/articles/using-a-hibernate-interceptor-) OR an event-listener http://leakfromjavaheap.blogspot.com/2013/08/prepersist-and-preupdate-not-working.html & https://timezra.blogspot.com/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

        Reply
      • A M Bharath

        October 22, 2013

        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

        Reply
        • Lokesh Gupta

          October 22, 2013

          I will give preference to this solution:
          https://stackoverflow.com/questions/221611/creation-timestamp-and-last-update-timestamp-with-hibernate-and-mysql

          Reply
  79. sats

    October 17, 2013

    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

    Reply
    • Lokesh Gupta

      October 17, 2013

      check server logs for deployment errors. Please provide logs.

      Reply
      • sats

        October 17, 2013

        Here’s what I get:

        –removed other logs

        Caused by: java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
        …

        Reply
        • Lokesh Gupta

          October 17, 2013

          Which hibernate version? 3 or 4?

          Verify if you are not making same mistakes.

          https://stackoverflow.com/questions/7528862/exception-noclassdeffounderror-for-cacheprovider
          https://stackoverflow.com/questions/11978094/java-lang-classnotfoundexception-org-hibernate-cache-cacheprovider-exception-wh

          Reply
  80. yogesh gandhi

    October 16, 2013

    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

    Reply
  81. Akansh Bhatnagar

    October 16, 2013

    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.

    Reply
    • Lokesh Gupta

      October 16, 2013

      Are you using example code or your own? Which spring version you have? Can you please check if this class is present in spring.jar? If you are using your own code then does it bundle ear file also?

      Reply
      • yogesh gandhi

        October 17, 2013

        Dear Lokesh, I think you should add this solution to your post, as many people don’t read comments.

        Add one troubleshooting section and this is majorly faced by all new commers

        Reply
        • Lokesh Gupta

          October 17, 2013

          I will.

          Reply
    • yogesh gandhi

      October 17, 2013

      please add com.springsource.org.aopalliance-1.0.0.jar to your classpath. This doesn’t comes directly with spring 3. This is a known problem with spring 3.0

      See this link, it has given a clear cut solution…

      http://javaprogrammingtips4u.blogspot.com/2010/04/resolve-javalangnoclassdeffounderror.html

      Reply
  82. wuchiwo

    October 2, 2013

    LazyInitializationException thrown since the session has been closed.

    Reply
  83. Kalyan

    September 26, 2013

    I cannot download the source code from the below link. Do you have any other link to download source code.
    https://docs.google.com/file/d/0B7yo2HclmjI4clZVT0VxeGNERFk/edit?usp=sharing

    Reply
    • Lokesh Gupta

      September 26, 2013

      What’s problem in this??? Go to file menu and click download.

      Reply
  84. John

    September 25, 2013

    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
    Reply
    • Lokesh Gupta

      September 25, 2013

      java.lang.NoClassDefFoundError: org/hibernate/annotations/common/AssertionFailure
      It says everything. Dependency missing. Make sure you hace correct pom.xml file.

      Reply
  85. Andrew

    September 24, 2013

    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
    Reply
    • Lokesh Gupta

      September 24, 2013

      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

      Reply
  86. Nirmal

    September 23, 2013

    Hi
    I have copied all the files along with the required jars. I am using spring STS and vmware Server for deployment.

    Here I am connecting to DB using Oracle XE. But while launching the app, it’s throwing me http 404 error.

    Is this right context root I am using? Need your help..

    http://localhost:8081/Spring3HibernateIntegration/

    Reply
    • Lokesh Gupta

      September 23, 2013

      Path is correct. Look for some error in server logs while deployment.

      Reply
  87. iswarya

    September 20, 2013

    could u plz explain me the same project using weblogic server

    Reply
  88. iswarya

    September 20, 2013

    thank you so much. and ur sample project helped me a lot.
    thank u once again

    Reply
  89. Prashant

    September 18, 2013

    Great tutorial… It worked for me flawlessly….

    Reply
  90. Idree

    September 12, 2013

    I am getting null pointer exception

    Reply
    • Lokesh Gupta

      September 12, 2013

      Please share the stack trace.

      Reply
      • Idrees

        September 13, 2013

        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.
        
        Reply
        • Lokesh Gupta

          September 13, 2013

          Absolutely not helpful. I thought you was playing with my code sample, but it was something else. Better upload your code and share download link here.

          Reply
          • Idrees

            September 13, 2013

            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!

            Reply
            • Lokesh Gupta

              September 15, 2013

              I am already using autowiring, right? Read more about autowiring here: https://howtodoinjava.com/2013/05/08/spring-beans-autowiring-concepts/

              Reply
  91. Gowtham

    September 10, 2013

    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……

    Reply
    • Lokesh Gupta

      September 10, 2013

      Look at here: https://stackoverflow.com/questions/4219166/can-not-find-the-tag-library-descriptor-of-springframework

      Reply
  92. keda87

    September 9, 2013

    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

    Reply
  93. Anandan Rajendran

    September 4, 2013

    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)
    Reply
    • Lokesh Gupta

      September 5, 2013

      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.

      Reply
      • Lilliana

        May 14, 2014

        I had the same error, but it was beacause i put the hibernate.cfg.xml inside of this folders src/resources and the correct path was inside the source folder src/main/resources. Now the application is working correctly 😀 Thanks for this example and your help.

        Reply
  94. sudhindra

    August 26, 2013

    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..?

    Reply
    • Lokesh Gupta

      August 26, 2013

      Make sure you have defined @ModelAttribute(value=”employee”) in controller. Please refer to code above. Its working and tested in tomcat.

      Reply
  95. Pradeep

    August 24, 2013

    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

    Reply
    • Lokesh Gupta

      August 24, 2013

      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: https://howtodoinjava.com/spring/spring-restful/how-to-write-restful-webservices-using-spring-3-mvc/

      Reply
      • Pradeep

        August 25, 2013

        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?

        Reply
        • Lokesh Gupta

          August 25, 2013

          Refer: https://stackoverflow.com/questions/736186/can-a-spring-form-command-be-a-map

          Reply
  96. sudhindra

    August 23, 2013

    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..

    Reply
    • Lokesh Gupta

      August 23, 2013

      I am sorry but I have no idea around netbeans IDE.

      Reply
      • sudhindra

        August 24, 2013

        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

        Reply
        • Lokesh Gupta

          August 24, 2013

          Sorry buddy, can’t help with only this much information. May be you can upload your project to google docs and provide a link here. Then only somebody can help you.

          Reply
  97. kehinde

    August 23, 2013

    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.

    Reply
  98. deepak singh

    August 18, 2013

    hi Lokesh,
    it worked after i added
    on top of jsp page

    thanks
    Deepak singh

    Reply
  99. deepak singh

    August 18, 2013

    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??

    Reply
    • anmol

      September 24, 2013

      i am facing same the problem.
      have you solved the problem?
      please help me.

      Reply
  100. Alonso Isidoro Roman

    August 16, 2013

    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.

    Reply
  101. ken4ward

    August 14, 2013

    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 [&quot;http-bio-8585&quot;]
    Aug 14, 2013 2:46:19 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler [&quot;ajp-bio-8099&quot;]
    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 [&quot;http-bio-8585&quot;]
    Aug 14, 2013 2:46:28 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler [&quot;ajp-bio-8099&quot;]
    Aug 14, 2013 2:46:28 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 9763 ms
    Reply
    • Lokesh Gupta

      August 14, 2013

      Can you please list down the steps, you have done till now?

      Have you downloaded the source code, or integrating of your own?

      Reply
      • ken4ward

        August 14, 2013

        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.

        Reply
        • Lokesh Gupta

          August 14, 2013

          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.

          Reply
          • ken4ward

            August 14, 2013

            Ok. Thanks. But what I’m trying to avoid is maven because I have tried with little success in configuring it. Please, if possible do you have a sample of this that is not implement Maven?

            Reply
            • Lokesh Gupta

              August 14, 2013

              You can refer https://howtodoinjava.com/maven/ for maven installation and other simple tutorials. They are real easy.

              Reply
  102. Ajay

    August 3, 2013

    i am not able to download this project…Please can you mention the complete link..So in Just one shot i can download rar file..

    Thanks,
    Ajay

    Reply
    • Lokesh Gupta

      August 3, 2013

      Use link in file menu : File >> Download
      It will download the whole project

      Reply
      • siddharth

        August 13, 2013

        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

        Reply
        • Lokesh Gupta

          August 13, 2013

          Look at the bottom of post: “Download source code”. Its a link in bold. Click on that and proceed to download.

          Reply
          • Siddharth

            August 14, 2013

            Yes i got it ….Thank you so much for explanation…

            Reply
    • Ajay

      August 3, 2013

      Yes, i am able to do it…Thanks for nice explanation…

      Reply
  103. dharmendra

    July 17, 2013

    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.

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

    Reply
    • Lokesh Gupta

      July 18, 2013

      Annotation based configuration is not the topic in this post, so it is not here naturally.

      Reply
  104. Brijesh

    July 14, 2013

    Thanks for sharing

    Reply
  105. Brijesh

    July 7, 2013

    Wonderful post. Thanks for your effort.

    Reply
  106. kaushal pandya

    July 4, 2013

    Yes , I am able to see the follwoing msg , but do;nt know why not working in CMD.

    Browsing for this directory has been disabled.
    View this directory’s contents on https://search.maven.org/ instead.

    Reply
    • Lokesh Gupta

      July 4, 2013

      Your problem seems to be related to proxy which are normally configured in browsers, but not for CMD. Follow these instruction in given post to configure proxy settings for maven.

      https://howtodoinjava.com/maven/maven-proxy-settings/

      Reply
  107. Kaushal Pandya

    July 4, 2013

    When i am running first command I am getting follwing issue, please suggest

    Connection to http://repo.maven.apache.org refused

    Reply
    • Lokesh Gupta

      July 4, 2013

      Are you able to access this URL from browser. Do you get any access denied error in browser?

      Reply
      • Kaushal Pandya

        July 4, 2013

        Yes I am able to acces it .

        Reply
  108. JOO

    June 18, 2013

    i downloaded your source and imported it.
    and i launched the application(http://localhost:8080/Spring3HibernateIntegration/) but it doesn’t work.
    404 error message appeared
    i am using tomcat
    tell me anything how can i fix it T.T

    Reply
    • Lokesh Gupta

      June 18, 2013

      Probably you have not setup the database. Check for tomcat console logs for deployment errors.

      Reply
  109. anil

    May 8, 2013

    sorry its a spelling mistake from my side…its working very fine..thanks for ur tutorial

    Reply
    • Lokesh Gupta

      May 8, 2013

      Glad, you made it !!

      Reply
      • anil

        May 8, 2013

        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.

        Reply
        • Lokesh Gupta

          May 8, 2013

          Try setting update in

          node in employee-servlet.xml.
          Reply
          • anil

            May 8, 2013

            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

            Reply
  110. anil

    May 8, 2013

    tell me the url to launch the application

    Reply
    • Lokesh Gupta

      May 8, 2013

      Its http://localhost:8080/Spring3HibernateIntegration/

      Welcome file is configured as index.jsp in web.xml. So no need to type any relative URL.

      Reply
      • anil

        May 8, 2013

        i did the same…i am using weblogic i typed http://localhost:9090/Spring3HibernateIntegration/ where i changed my port number to 9090

        Reply
        • narendra

          November 22, 2013

          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)
          	
          Reply
          • Lokesh Gupta

            November 22, 2013

            I does not look like programmatic error. Something is missing on runtime in DB.

            Reply
          • Cyril

            December 7, 2013

            You have to create sequence for you table in the database.

            Reply

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap