Spring 3 and hibernate integration tutorial with example

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

spring 3 hibernate integration example

Employee management screen

Development environment

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

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

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

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

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

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

cd Spring3HibernateIntegration
mvn eclipse:eclipse -Dwtpversion=2.0

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

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

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

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

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

package com.howtodoinjava.entity;

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

@Entity
@Table(name="EMPLOYEE")
public class EmployeeEntity 
{
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
    @Column(name="FIRSTNAME")
    private String firstname;
    @Column(name="LASTNAME")
    private String lastname;
    @Column(name="EMAIL")
    private String email;
    @Column(name="TELEPHONE")
    private String telephone;
    //Add setters and getters
}

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

EmployeeDao.java

package com.howtodoinjava.dao;

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

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

EmployeeDaoImpl.java

package com.howtodoinjava.dao;

import java.util.List;

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

import com.howtodoinjava.entity.EmployeeEntity;

@Repository
public class EmployeeDaoImpl implements EmployeeDAO<br />
{
    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public void addEmployee(EmployeeEntity employee) {
        this.sessionFactory.getCurrentSession().save(employee);
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<EmployeeEntity> getAllEmployees() {
        return this.sessionFactory.getCurrentSession().createQuery("from EmployeeEntity").list();
    }
    @Override
    public void deleteEmployee(Integer employeeId) {
        EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load(
                EmployeeEntity.class, employeeId);
        if (null != employee) {
            this.sessionFactory.getCurrentSession().delete(employee);
        }
    }
}

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

EmployeeManager.java

package com.howtodoinjava.service;

import java.util.List;

import com.howtodoinjava.entity.EmployeeEntity;

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

EmployeeManagerImpl.java

package com.howtodoinjava.service;

import java.util.List;

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

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

@Service
public class EmployeeManagerImpl implements EmployeeManager 
{
    @Autowired
    private EmployeeDAO employeeDAO;
    @Override
    @Transactional
    public void addEmployee(EmployeeEntity employee) {
        employeeDAO.addEmployee(employee);
    }
    @Override
    @Transactional
    public List<EmployeeEntity> getAllEmployees() {
        return employeeDAO.getAllEmployees();
    }
    @Override
    @Transactional
    public void deleteEmployee(Integer employeeId) {
        employeeDAO.deleteEmployee(employeeId);
    }
    public void setEmployeeDAO(EmployeeDAO employeeDAO) {
        this.employeeDAO = employeeDAO;
    }
}

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

EditEmployeeController.java

package com.howtodoinjava.controller;

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

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

@Controller
public class EditEmployeeController 
{
    @Autowired
    private EmployeeManager employeeManager;
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listEmployees(ModelMap map)
    {
        map.addAttribute("employee", new EmployeeEntity());
        map.addAttribute("employeeList", employeeManager.getAllEmployees());
        return "editEmployeeList";
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addEmployee(@ModelAttribute(value="employee") EmployeeEntity employee, BindingResult result)
    {
        employeeManager.addEmployee(employee);
        return "redirect:/";
    }
    @RequestMapping("/delete/{employeeId}")
    public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId)
    {
        employeeManager.deleteEmployee(employeeId);
        return "redirect:/";
    }
    public void setEmployeeManager(EmployeeManager employeeManager) {
        this.employeeManager = employeeManager;
    }
}

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

editEmployeeList.jsp

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

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

web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

<display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>/WEB-INF/index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>employee</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/employee-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

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

employee-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.howtodoinjava.controller" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties"></bean>
    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}"></bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>
    <bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean>
    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

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

hibernate.cfg.xml

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

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

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

jdbc.properties

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

messages_en.properties

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

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

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

Spring 3 hibernate integration project structure

Spring 3 hibernate integration project structure

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

Update:

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

More references:

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

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


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

Refer:

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

Happy Learning !!

240 thoughts on “Spring 3 and hibernate integration tutorial with example”

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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;

    Best regards
    Aina

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

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

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

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

    1. 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”);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  20. Dear Sir,

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

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

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

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

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

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

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

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

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

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

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

  29. Lokesh,

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

    Volleyball (instead of Spring3HibernateIntegration)

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

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

    Also, I am using Tomcat instead of JBoss.

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

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

    I will gladly post the code if you request so.

    Thanks and thanks for the excellent tutorial.

    Mike

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

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

      See if your URL is scanned and registered.

      1. Lokesh,

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

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

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

        Results :

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

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

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

              2) Concert to eclipse supported project
              cd vollyballs

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

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

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

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

    like

    public class XX
    {
    public String AA()
    {

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

    }

    public String BB()
    {

    }

    }

    public class YY

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

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

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

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

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

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

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


seven + = 12

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>