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

Lokesh

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

You may also like...

215 Responses

  1. Venky says:

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

  2. Aina G says:

    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

    • Lokesh says:

      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

      • Aina G says:

        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

      • Aina G says:

        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

  3. amarnath says:

    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.

    • Lokesh says:

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

    • amarnath says:

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

  4. ravi says:

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

    • Lokesh says:

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

  5. Wilfredo G. says:

    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

  6. Lilliana says:

    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?

    • Lokesh says:

      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>
      
  7. anil says:

    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

  8. Binh Tran says:

    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.

    • Lokesh says:

      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?

      • Binh Tran says:

        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.

        • Lokesh says:

          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.

  9. prem says:

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

  10. riya says:

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

    • Sandeep says:

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

  11. bernard says:

    Thank-you so much for the work done

  12. Mohan says:

    Hi Lokesh,

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

  13. Surendra says:

    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 http://stackoverflow.com/questions/22606636/spring-hibernate-sql-entity-name-not-resolved

  14. Vipin says:

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

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

    • Lokesh says:

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

      • Lokesh says:

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

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

  15. Vipin says:

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

    • Lokesh says:

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

  16. harish says:

    Dear Sir,

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

  17. Praveen says:

    Thanks for providing working model to get started with.

  18. ganesh says:

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

  19. Binh Thanh Nguyen says:

    Thanks, nice post.

  20. Prashanth says:

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

  21. Siva says:

    Hi Lokesh,

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

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

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

    Thanks,
    Siva

  22. Vijay says:

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

  23. Manisha Pandey says:

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

    • Lokesh says:

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

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

  24. kalyan says:

    really useful …thank u so much :)

  25. Piyush Grover says:

    Thanks Lokesh sir. Awesome post.

  26. Andrew says:

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

    • Lokesh says:

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

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

  27. velmurugan says:

    Hi Lokesh,

    I am getting below error.

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

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

  28. Roushan says:

    thanks Sir u r doing a very helpful work.

  29. Venkata Sriram says:

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

    Thanks
    Venkata Sriram

  30. sarojineveen says:

    i am facing this error can you please help me.

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

  31. nadhine says:

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

    Sorry for my english GTranslate

  32. Mike says:

    Lokesh,

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

    Volleyball (instead of Spring3HibernateIntegration)

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

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

    Also, I am using Tomcat instead of JBoss.

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

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

    I will gladly post the code if you request so.

    Thanks and thanks for the excellent tutorial.

    Mike

  33. Venkata Sriram says:

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

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

    like

    public class XX
    {
    public String AA()
    {

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

    }

    public String BB()
    {

    }

    }

    public class YY

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

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

    • Lokesh Gupta says:

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

      • Venkata Sriram says:

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

        • Lokesh Gupta says:

          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?

          • Venkata Sriram says:

            ok sir .Thanks for clarification sir.

          • rajeshboy44 says:

            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

            • Lokesh Gupta says:

              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.

  34. Dilip says:

    Its working fine , gr8 .. test .Thanks

  35. amit says:

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

  36. Sebastian says:

    Hello, can you help with this error?
    SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4149)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

  37. helios says:

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

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

  38. Andros says:

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

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

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

  39. A M Bharath says:

    Hello Lokesh,

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

    Eg:

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

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

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

    Sincerely,
    A M Bharath

    • Lokesh Gupta says:

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

      • A M Bharath says:

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

        Sincerely,
        A M Bharath

  40. Akram says:

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

  41. prasanta says:

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

  42. santhosh says:

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

  43. santhosh says:

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

  44. Dinesh says:

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

  45. Dilli says:

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

  46. Tyrone says:

    Hi Lokesh

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

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

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

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

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

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

  49. Das Kumar says:

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

  50. Das Kumar says:

    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 ?

  51. Sandeep Tyagi says:

    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?

  52. Arun Kumar says:

    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.

  53. Bharath says:

    Hi Lokesh,

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

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

  54. sats says:

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

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

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

  55. yogesh gandhi says:

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

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

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

    While earlier it was

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

  56. Akansh Bhatnagar says:

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

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

    Please help in this.

  57. wuchiwo says:

    LazyInitializationException thrown since the session has been closed.

  58. Kalyan says:

    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

  59. John says:

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

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

  60. Andrew says:

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

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

    • Lokesh Gupta says:

      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

  61. Nirmal says:

    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/

  62. iswarya says:

    could u plz explain me the same project using weblogic server

  63. iswarya says:

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

  64. Prashant says:

    Great tutorial… It worked for me flawlessly….

  65. Idree says:

    I am getting null pointer exception

    • Lokesh Gupta says:

      Please share the stack trace.

      • Idrees says:


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

        application-context.xml

        org.hibernate.dialect.MySQLDialect
        true

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

        WRITE_DATES_AS_TIMESTAMPS

  66. Gowtham says:

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

  67. keda87 says:

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

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

  68. Anandan Rajendran says:

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

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

    • Lokesh Gupta says:

      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.

      • Lilliana says:

        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 :D Thanks for this example and your help.

  69. sudhindra says:

    hi i am getting error like this:
    type Exception report

    message

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

    exception

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

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

    what to do..?

  70. Pradeep says:

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

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

    Regards,
    Pradeep

  71. sudhindra says:

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

    • Lokesh Gupta says:

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

      • sudhindra says:

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

        package service;

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

        public class TestSpringHibernateDaoSupport {

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

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

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

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

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

        error:

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

        its a spring hibernate integration program

        • Lokesh Gupta says:

          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.

  72. kehinde says:

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

  73. deepak singh says:

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

    thanks
    Deepak singh

  74. deepak singh says:

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

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

  76. ken4ward says:

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

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

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

    • Lokesh Gupta says:

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

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

      • ken4ward says:

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

  77. Ajay says:

    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

  78. dharmendra says:

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

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

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

  79. Brijesh says:

    Thanks for sharing

  80. Brijesh says:

    Wonderful post. Thanks for your effort.

  81. kaushal pandya says:

    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 http://search.maven.org instead.

  82. Kaushal Pandya says:

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

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

  83. JOO says:

    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

  84. anil says:

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

    • Lokesh Gupta says:

      Glad, you made it !!

      • anil says:

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

        • Lokesh Gupta says:

          Try setting update in

          node in employee-servlet.xml.
          • anil says:

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

  85. anil says:

    tell me the url to launch the application

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


Want to ask any question? Or suggest anything?