Spring MVC Hibernate MySQL Integration CRUD Example Tutorial

Filed Under: Hibernate

We learned how to integrate Spring and Hibernate in our last tutorial. Today we will move forward and integrate Spring MVC and Hibernate frameworks in a web application CRUD example.

Our final project structure looks like below image, we will look into each of the components one by one.

Spring MVC Hibernate Example

Note that I am using Spring 4.0.3.Release and Hibernate 4.3.5.Final versions for our example, the same program is also compatible for Spring 4 and Hibernate 3, however you need to make small changes in spring bean configuration file discussed in the last tutorial.

Maven Dependencies

Let’s look at all the maven dependencies are required for hibernate and spring MVC framework integration.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.journaldev.spring</groupId>
	<artifactId>SpringMVCHibernate</artifactId>
	<name>SpringMVCHibernate</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>4.0.3.RELEASE</org.springframework-version>
		<org.aspectj-version>1.7.4</org.aspectj-version>
		<org.slf4j-version>1.7.5</org.slf4j-version>
		<hibernate.version>4.3.5.Final</hibernate.version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		
		<!-- Apache Commons DBCP -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<!-- Spring ORM -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>

Some of the dependencies above are included by STS (Spring Tool Suite) when I create Spring MVC project. Important dependencies above are spring-context, spring-webmvc, spring-tx, hibernate-core, hibernate-entitymanager and spring-orm. I am using Apache Commons DBCP for connection pooling, but in real life situations, most probably you have connection pooling done by the container and all we need is to provide the JNDI reference details to use.

NOTE: I noticed that some of the readers are getting database connection issues. Notice that in my pom.xml, there is no database driver. That works for me because I have MySQL driver in tomcat lib directory and some DataSource connections configured with it. For any database connection related issues, either put the database driver in container lib or include that in pom.xml dependencies.

Deployment Descriptor

We need to plugin the spring framework in our web application, that is done by configuring Spring framework DispatcherServlet as the front controller. Our web.xml file looks like below.


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

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Most of the part is boilerplate code, most important part is the spring context file location where we will configure our spring beans and services. If you want, you can change them according to your project requirements.

Hibernate Entity Bean

We are using JPA annotations in our entity bean class, however, we can also have a simple java bean and mapping details in the XML file. In that case, we need to provide mapping file details while configuring Hibernate SessionFactory in spring bean configurations.


package com.journaldev.spring.model;

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

/**
 * Entity bean with JPA annotations
 * Hibernate provides JPA implementation
 * @author pankaj
 *
 */
@Entity
@Table(name="PERSON")
public class Person {

	@Id
	@Column(name="id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private int id;
	
	private String name;
	
	private String country;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
	
	@Override
	public String toString(){
		return "id="+id+", name="+name+", country="+country;
	}
}

Our entity bean maps to PERSON table in MySQL database, notice that I have not annotated “name” and “country” fields with @Column annotation because they are of the same name. Below SQL script shows the table details.


CREATE TABLE `Person` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  `country` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Hibernate DAO Implementation

We will create PersonDAO interface to declare the methods that we will use in our project. Next, we will provide hibernate specific implementation for it.


package com.journaldev.spring.dao;

import java.util.List;

import com.journaldev.spring.model.Person;

public interface PersonDAO {

	public void addPerson(Person p);
	public void updatePerson(Person p);
	public List<Person> listPersons();
	public Person getPersonById(int id);
	public void removePerson(int id);
}

Hibernate-specific DAO implementation looks like below.


package com.journaldev.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.journaldev.spring.model.Person;

@Repository
public class PersonDAOImpl implements PersonDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sf){
		this.sessionFactory = sf;
	}

	@Override
	public void addPerson(Person p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(p);
		logger.info("Person saved successfully, Person Details="+p);
	}

	@Override
	public void updatePerson(Person p) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(p);
		logger.info("Person updated successfully, Person Details="+p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> listPersons() {
		Session session = this.sessionFactory.getCurrentSession();
		List<Person> personsList = session.createQuery("from Person").list();
		for(Person p : personsList){
			logger.info("Person List::"+p);
		}
		return personsList;
	}

	@Override
	public Person getPersonById(int id) {
		Session session = this.sessionFactory.getCurrentSession();		
		Person p = (Person) session.load(Person.class, new Integer(id));
		logger.info("Person loaded successfully, Person details="+p);
		return p;
	}

	@Override
	public void removePerson(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		Person p = (Person) session.load(Person.class, new Integer(id));
		if(null != p){
			session.delete(p);
		}
		logger.info("Person deleted successfully, person details="+p);
	}

}

Notice that I am not using Hibernate Transaction, that is because it will be taken care by Spring framework.

Spring Service Classes

Here are our service classes that are using Hibernate DAO classes to work with Person objects.


package com.journaldev.spring.service;

import java.util.List;

import com.journaldev.spring.model.Person;

public interface PersonService {

	public void addPerson(Person p);
	public void updatePerson(Person p);
	public List<Person> listPersons();
	public Person getPersonById(int id);
	public void removePerson(int id);
	
}

package com.journaldev.spring.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.journaldev.spring.dao.PersonDAO;
import com.journaldev.spring.model.Person;

@Service
public class PersonServiceImpl implements PersonService {
	
	private PersonDAO personDAO;

	public void setPersonDAO(PersonDAO personDAO) {
		this.personDAO = personDAO;
	}

	@Override
	@Transactional
	public void addPerson(Person p) {
		this.personDAO.addPerson(p);
	}

	@Override
	@Transactional
	public void updatePerson(Person p) {
		this.personDAO.updatePerson(p);
	}

	@Override
	@Transactional
	public List<Person> listPersons() {
		return this.personDAO.listPersons();
	}

	@Override
	@Transactional
	public Person getPersonById(int id) {
		return this.personDAO.getPersonById(id);
	}

	@Override
	@Transactional
	public void removePerson(int id) {
		this.personDAO.removePerson(id);
	}

}

Notice that spring declarative transaction management is applied by using @Transactional annotation.

Spring Controller Class

Our DAO and Service classes are ready, it’s time to write our controller class that will take care of client requests and uses service classes to perform database specific operations and then returns the view pages.


package com.journaldev.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.journaldev.spring.model.Person;
import com.journaldev.spring.service.PersonService;

@Controller
public class PersonController {
	
	private PersonService personService;
	
	@Autowired(required=true)
	@Qualifier(value="personService")
	public void setPersonService(PersonService ps){
		this.personService = ps;
	}
	
	@RequestMapping(value = "/persons", method = RequestMethod.GET)
	public String listPersons(Model model) {
		model.addAttribute("person", new Person());
		model.addAttribute("listPersons", this.personService.listPersons());
		return "person";
	}
	
	//For add and update person both
	@RequestMapping(value= "/person/add", method = RequestMethod.POST)
	public String addPerson(@ModelAttribute("person") Person p){
		
		if(p.getId() == 0){
			//new person, add it
			this.personService.addPerson(p);
		}else{
			//existing person, call update
			this.personService.updatePerson(p);
		}
		
		return "redirect:/persons";
		
	}
	
	@RequestMapping("/remove/{id}")
    public String removePerson(@PathVariable("id") int id){
		
        this.personService.removePerson(id);
        return "redirect:/persons";
    }
 
    @RequestMapping("/edit/{id}")
    public String editPerson(@PathVariable("id") int id, Model model){
        model.addAttribute("person", this.personService.getPersonById(id));
        model.addAttribute("listPersons", this.personService.listPersons());
        return "person";
    }
	
}

Notice that I am using @Controller annotation, so that Spring framework will treat it as a Controller class to handle client requests. Also I am using @Autowired and @Qualifier annotations for injecting PersonService, we could have done it in the spring context xml file too.

Recommended Read: Spring Bean Autowiring

Spring Bean Configuration

Our services are ready, all we need is to wire them through spring bean configurations. Our root-context.xml file is empty, so we will look only into the servlet-context.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<beans:property name="url"
			value="jdbc:mysql://localhost:3306/TestDB" />
		<beans:property name="username" value="pankaj" />
		<beans:property name="password" value="pankaj123" />
	</beans:bean>

	<!-- Hibernate 4 SessionFactory Bean definition -->
	<beans:bean id="hibernate4AnnotatedSessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="annotatedClasses">
			<beans:list>
				<beans:value>com.journaldev.spring.model.Person</beans:value>
			</beans:list>
		</beans:property>
		<beans:property name="hibernateProperties">
			<beans:props>
				<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
				</beans:prop>
				<beans:prop key="hibernate.show_sql">true</beans:prop>
			</beans:props>
		</beans:property>
	</beans:bean>
	
	<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
		<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
		<beans:property name="personDAO" ref="personDAO"></beans:property>
	</beans:bean>
	<context:component-scan base-package="com.journaldev.spring" />
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>

</beans:beans>

dataSource bean is defined for org.apache.commons.dbcp.BasicDataSource class for basic connection pooling.

org.springframework.orm.hibernate4.LocalSessionFactoryBean bean is used for Hibernate 4 SessionFactory. For Hibernate 3, you will find similar classes as org.springframework.orm.hibernate3.LocalSessionFactoryBean and org.springframework.orm.hibernate3.AnnotationSessionFactoryBean.

One important point is that when we are depending on Spring framework for Hibernate Session management, we should not define hibernate.current_session_context_class, otherwise, you will get a lot of session transaction-related issues.

personDAO and personService beans are self understood.

transactionManager bean definition for org.springframework.orm.hibernate4.HibernateTransactionManager is required for Spring ORM to support hibernate session transaction management. For Hibernate 3, you will find similar class as org.springframework.orm.hibernate3.HibernateTransactionManager. Spring uses AOP for transaction management, you can now relate it with @Transactional annotation.

Recommended Read: Spring AOP and Spring Transaction Management

View Page

Our last part of the application is the view page, notice the attributes added to Model in Controller handler methods, we will use them to create our view page. We will also use JSTL tags, spring core and spring form tags.


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
	<title>Person Page</title>
	<style type="text/css">
		.tg  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
		.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
		.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
		.tg .tg-4eph{background-color:#f9f9f9}
	</style>
</head>
<body>
<h1>
	Add a Person
</h1>

<c:url var="addAction" value="/person/add" ></c:url>

<form:form action="${addAction}" commandName="person">
<table>
	<c:if test="${!empty person.name}">
	<tr>
		<td>
			<form:label path="id">
				<spring:message text="ID"/>
			</form:label>
		</td>
		<td>
			<form:input path="id" readonly="true" size="8"  disabled="true" />
			<form:hidden path="id" />
		</td> 
	</tr>
	</c:if>
	<tr>
		<td>
			<form:label path="name">
				<spring:message text="Name"/>
			</form:label>
		</td>
		<td>
			<form:input path="name" />
		</td> 
	</tr>
	<tr>
		<td>
			<form:label path="country">
				<spring:message text="Country"/>
			</form:label>
		</td>
		<td>
			<form:input path="country" />
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<c:if test="${!empty person.name}">
				<input type="submit"
					value="<spring:message text="Edit Person"/>" />
			</c:if>
			<c:if test="${empty person.name}">
				<input type="submit"
					value="<spring:message text="Add Person"/>" />
			</c:if>
		</td>
	</tr>
</table>	
</form:form>
<br>
<h3>Persons List</h3>
<c:if test="${!empty listPersons}">
	<table class="tg">
	<tr>
		<th width="80">Person ID</th>
		<th width="120">Person Name</th>
		<th width="120">Person Country</th>
		<th width="60">Edit</th>
		<th width="60">Delete</th>
	</tr>
	<c:forEach items="${listPersons}" var="person">
		<tr>
			<td>${person.id}</td>
			<td>${person.name}</td>
			<td>${person.country}</td>
			<td><a href="<c:url value='/edit/${person.id}' />" >Edit</a></td>
			<td><a href="<c:url value='/remove/${person.id}' />" >Delete</a></td>
		</tr>
	</c:forEach>
	</table>
</c:if>
</body>
</html>

Spring MVC Hibernate Application Testing

Just build and deploy the project into any servlet container of your choice, for example, Tomcat. Below screenshots shows the view pages for our application.

Spring MVC Hibernate

Java Spring MVC Hibernate MySQL

You will also find similar logs in the server log file.


Hibernate: insert into PERSON (country, name) values (?, ?)
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person saved successfully, Person Details=id=15, name=Pankaj, country=USA
Hibernate: select person0_.id as id1_0_, person0_.country as country2_0_, person0_.name as name3_0_ from PERSON person0_
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=10, name=Raman, country=UK2
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=11, name=Lisa, country=France
INFO : com.journaldev.spring.dao.PersonDAOImpl - Person List::id=15, name=Pankaj, country=USA

Summary

This tutorial was aimed to provide sufficient details for you to getting started with Spring MVC and Hibernate integration, I hope you will find it useful. You can download the final project from below link and play around with it.

You can also checkout the project from our GitHub Repository.

Comments

  1. Gopalakrishnan T says:

    Can you please deploy the web app in Nginx.

  2. saera says:

    HI,

    Did anyone face the issue : Multiple annotations found at this line: The referenced file contains error in servlet-context.xml?

  3. Nilesh says:

    Error : 404 with warning

    INFO: Server startup in [15,727] milliseconds
    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

  4. Suneth says:

    It worked after some changes, Thanks for the example.

    1. Yash Patel says:

      can you send me this projects on my email id :- yashp497@gmail.com

  5. Saurav says:

    Hey Guys, the example is running absolutely fine doesn’t have any errors just you have to make few changes before running it. The changes are:
    Edit username and password for the database as per yours in the configuration file.
    add an update or else you may get SQLGrammar exception
    and just run the program see to it path will be
    http://localhost:8888/SpringMVCHibernate/persons

  6. srinath says:

    HTTP Status 404 – Not Found

    Type Status Report

    Message /SpringMVCHibernate/WEB-INF/views/person.jsp

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    Apache Tomcat/9.0.20
    ———————————————————————————————————-

    in console: INFO: Server startup in [9,904] milliseconds
    Hibernate: select person0_.id as id1_0_, person0_.country as country2_0_, person0_.name as name3_0_ from PERSON person0_

    i am getting 404 error but without error can you please tell me what is the problem

    1. srinath says:

      i found the mistake in controller listPersons() method we are return person(change to Person) if any body got this problem it will help

  7. jim says:

    Thank you, Pankaj for the article. It was easy to get through.

    I get this error while adding a new person

    HTTP Status 500 – Internal Server Error

    Type Exception Report

    Message Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

    Exception

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    Root Cause

    org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:203)
    org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:681)
    org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:563)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
    org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy26.updateBook(Unknown Source)
    com.app.book.controller.BookController.addBook(BookController.java:48)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

  8. Raj says:

    I have downlaoded above project and deploy it after that when we run it as server we get below error
    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    how can i resolve it

  9. Jeremy. T. Kingsbury says:

    There are too many comments on this page.
    Also, I’m testing the email authentication process.

  10. ShivaPrasad says:

    2 errors are showing up on running the project which results in ClassNotFoundException and driver not found .To resolve below are to be added in the project
    1.PersonDAO is to be autowired in the PersonServiceImpl
    2.mysql driver dependancy is to be added in the POM .xml

  11. Nitin Rathod says:

    Why PersonDao and SessionFactory objects are not autowired and how there objects are being injected.

  12. Anupam Kumar Thakur says:

    Hi Pankaj

    I have configured project. But how to run this project on tomcat. When I do MVN Build it’s show an error.

    [INFO] ————————————————————————
    [ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format : or :[:]:. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException

  13. Ravinder says:

    Tutorial was excellent but where the log messages are printed

  14. Akshay says:

    How can i get json response in the same code?

  15. Michal H says:

    Why don’t you use EntityManager?

  16. Aishwarya says:

    How should i connect it to mysql. Do I need to create tables there. Please let me know the whole procedure

    1. av says:

      yes you have to create table first in database as mentioned above

  17. Mangesh says:

    Hi Pankaj,

    Getting this issue not able resolved can you please help me

    ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper – Cannot create PoolableConnectionFactory (Could not create connection to database server.)

    Servlet.service() for servlet [appServlet] in context with path [/SpringMVCHibernate] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection] with root cause

  18. herbert says:

    a couple of features for this project work fine but also some aint okey,try reviewing it

  19. Shyam J says:

    I am getting this error,please help me.I checked everything & it seems all ok.

    HTTP Status 404 – Not Found
    Type Status Report

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    Apache Tomcat/8.5.34

    1. Pankaj says:

      Debugging Steps:

      1. What is the URL you are hitting?
      2. What is the WAR file name deployed on the tomcat server?
      3. Check server logs to see if there are any errors in deployment?

    2. Sergei says:

      1 Check your log
      2 Did you create Data Base? if you didnt do that create “TestDB” in Mysql and you need to correct servlet-context.
      3 correct like this @RequestMapping(value = {“/persons”,”/”}, method = RequestMethod.GET)
      4 add in pom.xml this dependency

      mysql
      mysql-connector-java
      5.1.6

      5 if it didnt deploy check your log if it is hibernate You need to add property in servlet-context
      update

  20. BalaKrishna says:

    Hi Pankaj,

    There are so many issues in the project attached,
    Please recorrect it if you can or delete the post.
    Please dont test the patience of those who run this project.

    Regards,
    Balu

    1. Pankaj says:

      Hi Bala,

      First of all, the project runs fine. As a proof, you can see that I have provided images of the sample execution of the application.

      Now coming to your point that there are various errors in the project, have you ever thought that it might be because of some changes made by you in the project, or in your MySQL DB or server instance or your java environment?

      What did you try to fix the issue? Just saying that you are getting issue will not help anyone.

      The project is hosted on GitHub, you are more than welcome to Fork it and fix any issues you find and submit a PR if you really want to help everyone.

  21. GOVIND says:

    Thanks to you and simple explanation

  22. Udhaya Prakash M says:

    It works fine. Now I want to add some operations as I need. In a similar way, I create controller, services, dao and model. But I don’t know how to define it beans and call. How to achieve this.

  23. balakrishna says:

    working without any issues, Thanks

  24. Erick García says:

    Thank you very much Pankaj, I am new to this topic and your example is very useful.
    I greet you from Mexico

  25. prafull says:

    For 404 not found error

    try this
    @RequestMapping(value = {“/persons”,”/”}, method = RequestMethod.GET)
    and please add database connector jar file according to your database, change the servlet-context.xml file according to that.

    it will work fine

  26. Gokul Ramalingam says:

    org.hibernate.engine.jdbc.spi.SqlExceptionHelper – Cannot create PoolableConnectionFactory (CLIENT_PLUGIN_AUTH is required)

  27. ram says:

    Hi Pankaj,
    Thanks for your tutorial,Though i am able to deploy your code i am facing an issue with the jsps,Whenever i hit the persons jsp page it is not showing any textfields,It is simply displaying two buttons with a table.Is it something related to jar spring form tag and its versions?Or should i need to add any more jar dependency.Any quick help is highly appreciated.

    1. Pankaj says:

      Can you check if there are any warnings related to TLD files?

      1. ram says:

        No pankaj there are no warnings…..Everything looks clean

  28. ram says:

    Hi Pankaj,
    I am facing an issue with the jsp,I am able to successfully deploy the code you have provided but when ever i hit the “https://localhost:8010/SpringMVCHibernate/persons”,Though the JSP page is displayed its test fields re not visible .I am getting two buttons with a table.Is it releated to jars in the pom?Plesae suggest me a turnaround.

  29. Vivek says:

    If any one get 404 do this following changes

    1.make this change in PersonController.java

    @RequestMapping(value = {“”,”/persons”}, method = RequestMethod.GET)

    2.add mysql connector jar in pom.xml as below

    mysql
    mysql-connector-java
    6.0.6

    3.now run as maven install and then Run as Run on Server

  30. S GINIGE says:

    Please any one help me for this..

    org.apache.jasper.JasperException: An exception occurred processing [WEB-INF/view/customer-form.jsp] at line [28]

    25: Id:
    26:
    27:
    28:
    29:
    30:
    31:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:593)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

    Root Cause
    java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘command’ available as request attribute
    org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:173)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:193)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:159)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:144)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:134)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117)
    org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
    org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:345)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
    org.apache.jsp.WEB_002dINF.view.customer_002dform_jsp._jspx_meth_form_005finput_005f0(customer_002dform_jsp.java:286)
    org.apache.jsp.WEB_002dINF.view.customer_002dform_jsp._jspx_meth_form_005fform_005f0(customer_002dform_jsp.java:203)
    org.apache.jsp.WEB_002dINF.view.customer_002dform_jsp._jspService(customer_002dform_jsp.java:147)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)

    1. Sanjay says:

      is this problem solved or not? I am getting same

  31. Prakash Murugan says:

    public String listPersons(Model model)

    In this line, Model refers what? and From it get value for model?

  32. manoranjan says:

    type Exception report

    message The absolute uri: http://www.springframework.org/tags cannot be resolved in either web.xml or the jar files deployed with this application

    description

    The server encountered an internal error that prevented it from fulfilling this request.
    
    exception
    
    org.apache.jasper.JasperException: The absolute uri: http://www.springframework.org/tags cannot be resolved in either web.xml or the jar files deployed with this application
    	org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:55)
    	org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:277)
    	org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:75)
    	org.apache.jasper.compiler.TagLibraryInfoImpl.generateTldResourcePath(TagLibraryInfoImpl.java:250)
    	org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:125)
    	org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:421)
    	org.apache.jasper.compiler.Parser.parseDirective(Parser.java:479)
    	org.apache.jasper.compiler.Parser.parseElements(Parser.java:1435)
    	org.apache.jasper.compiler.Parser.parse(Parser.java:139)
    	org.apache.jasper.compiler.ParserController.doParse(ParserController.java:227)
    	org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
    	org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:201)
    	org.apache.jasper.compiler.Compiler.compile(Compiler.java:358)
    	org.apache.jasper.compiler.Compiler.compile(Compiler.java:338)
    	org.apache.jasper.compiler.Compiler.compile(Compiler.java:325)
    
  33. Abhishek Mishra says:

    Thank you so much its working fine 🙂

  34. demo says:

    You need to add mysql connector from mvn repository in POM.xml and also add the same in class path for apache run time without which you might face errors.

  35. naveen says:

    Hi pankaj,

    can you please help us in writing JUNIT for validating the DAO in this example please

    1. Pankaj says:

      What is the WAR file name you deployed, that will become the servlet context of the app.

  36. Krishna says:

    Two steps to fix this-
    1. Rename mapping for default first page, i.e. rename “/persons”, by “/”,
    2. Right click on project and Run As -> Maven Install.

    Now Run project, Hope this help !!!!

  37. mhmdsw says:

    hello , thanks to our tuturial , but my question is i want to integrate a basic authentification to this example with mysql database using person table with field user and password , my problem is i want integrate a ValidUser methode to te DAOiml in order to count a user with hibernate session and return a result to the controller . if a result of ValidUser is != 0 the login is success . my very problem is hibernate count . please help me . thanks

  38. castulo says:

    Awesome Tutorial so I wonder How I could download the example, thanks.

  39. Pranay says:

    Bro…you really saved my ass!
    Such a nice tutorial and awesome explanation !!
    I really appreciate what you’re doing…
    Keep up the good work!

    Thank you once again for your wonderful tutorial 🙂

  40. Roberto says:

    Hi Panjak,

    According to this post, it’s not recommended to use sessionFactory.getCurrentSession in a multithread environment. (i.e in a webapp).
    Why do you use getCurrentSession method in PersonDAOImpl class?

    Thank you

  41. nimesh pahadi says:

    thanks a lot Pankaj !!! very well explained, really helpful

  42. suman says:

    I am getting the classic Cannot create JDBC driver of class ” for connect URL ‘null’ when trying to get a connection from the jndi datasource. I am using Tomcat 8.5 and trying to connect to Microsoft SQL Server database.

  43. Pavan says:

    HTTP ERROR: 404

    Problem accessing /. Reason:

    NOT_FOUND
    Powered by Jetty://

  44. Neha says:

    Getting below error while trying to load person.jsp. Please help 🙁

    HTTP Status 404 –

    type Status report

    message

    description The requested resource is not available.

    Apache Tomcat/7.0.47

  45. Dattatray Dethe says:

    Hi Pankaj,
    Thats working fine .
    Thanks.
    Dattatray.

  46. Masthan says:

    it’s working Fine…Thanks

  47. Rony says:
    Class dependency error 'org/springframework/core/Ordered' occurred on aspect definition 'Aspect definition [\SpringMVCHibernate\src\main\webapp\WEB-INF\spring\appServlet
     \servlet-context.xml:63] advise type [after] advise [org.springframework.transaction.interceptor.TransactionInterceptor.invoke]' while processing bean 
     'org.springframework.web.servlet.view.InternalResourceViewResolver#SpringMVCHibernate#src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml#23 (23) 
     [org.springframework.web.servlet.view.InternalResourceViewResolver]'. Check if builder classpath is complete
    
    

    I am getting above error in the dispatcher servlet. Please help me sir.

  48. Junior says:

    Excelente ejemplo, te felicito y espero sigas ayudando con estos extraordinarios ejemplos, muchas gracias

  49. Rajesh says:
    HTTP Status 500 - Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    
    org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    	org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    	org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    	org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    	org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    	org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
    	org.hibernate.loader.Loader.getResultSet(Loader.java:2066)
    	org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1863)
    	org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
    	org.hibernate.loader.Loader.doQuery(Loader.java:910)
    	org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
    	org.hibernate.loader.Loader.doList(Loader.java:2554)
    	org.hibernate.loader.Loader.doList(Loader.java:2540)
    	org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
    	org.hibernate.loader.Loader.list(Loader.java:2365)
    	org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
    	org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    
  50. Anupkumar Mahamalla says:

    Hi pakaj,

    Just want to thanks for this nice article.
    I was looking for this type of perfect Example of Spring MVC-Hibernate-Mysql Example .
    Many peoples are facing the 404 issues, because there is no index page.
    I request to you to add index page, so that people can easily run this example

  51. Ganesh says:

    it’s working Fine…Thanks

  52. Avinash says:

    Hi

    I don’t know why i’m getting this Warn [error]

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    and return 404 error

    1. Anupkumar Mahamalla says:

      try with url: http://localhost:8080/SpringMVCHibernate/persons

      1. a says:

        No mapping found for HTTP request with URI [/SpringMVCHibernate/persons] in DispatcherServlet with name ‘servlet’

        error coming

    2. Amit kumar says:

      Just hit below url:

      http://localhost:8080/SpringMVCHibernate/persons

      if you are still getting error just add the below dependency in pom.xml.

      mysql
      mysql-connector-java
      5.1.31

  53. Ankit says:

    nice article

    I have a question,you have @transactional attribute without readonly = false,still it is saving/updating records.how?

  54. MIke says:

    It’s works for me. Nice work

  55. virendra says:

    very nice tutorial finally it works for me with little tweak

  56. Uttam says:

    Nice Demo for begginers. This works perfect. what is the use of root-context.xml??? can we run this without root-context.xml???

    plz reply as soon as possible……

    Thank you..

  57. sandeep jain says:

    Hi Pankaj,

    Cannot resolve this as 
    Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name 'personDAO' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl
    	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1327)
    	at
    
    1. Gulab says:

      Create Setter Method for “PersonDAO” in “PersonServiceAImpl”

  58. aayush says:

    Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4

    1. Arun says:

      put latest version of data base dependency

  59. aayush says:

    HTTP Status 404 – /SpringMVCHibernate/person
    type Status report

    message /SpringMVCHibernate/person

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/8.0.12

    what to do with this error

    1. aayush says:

      Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl

      why this erro coming

      1. Gulab says:

        Create Setter Method for “PersonDAO” in “PersonServiceAImpl”

    2. Gulab says:

      try with this url: http://localhost:8080/SpringMVCHibernate/persons

      1. a says:

        still its not working.what goes wrong?

  60. Selven says:

    Hi,
    I can access database, fetch values and print on the console. but the problem is unable to pass this data to JSP. local host says 404 error.

    1. Gulab says:

      check the “Requesting mapping Url” and In JSP

  61. ismail fedakar says:

    Merhaba Pankaj.
    Kardeşim bu projeyide çalıştıramadım. Nedenini araştırıyorum her türlü deneme yapıyorum ama çalışmıyor. Bu projelerin güncel versyonlarını koysan olmazmı. İnanki çok zaman kaybediyoruz. Bunca emek harcıyorsunuz. Sizede yazık bizede yazık.
    Kolay Gelsin.

  62. ismail fedakar says:

    Merhaba pankaj.
    Ne yaptıysam bu proje çalışmıyor kardeşim. Projelerin güncel versiyonlarını koysanız olmazmı.
    Bu projeler jdk 1.6 ile yapılmış ki artık eclips te varsayılan olarak gelmiyor. Windows 7 de zaten jdk 1.6 desteklemiyor.
    Boşa zaman kaybediyoruz. Yanlış anlama kardeşim buradan indirdiğim projelerin nerdeyse hiç biri çalışmıyor.
    Kolay Gelsin.

    1. Ismail Sen Cilginsin says:

      Arkadasim hasta misin sen? Adam biseyler ögretmek icin kendi istegiyle gayet aciklayarak ugrasarak proje koymus, sen sanki adamdan hizmet aliyormus para ödeyip karsilik bekliyormus gibi yazi yaziyorsun. Üstelik Türkce :))) hahaha ne manyaklar var ya.

  63. vowovrz says:

    1. In web.xml:

    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter

    encoding
    UTF-8

    forceEncoding
    true

    2. In pom.xml

    5.1.38

    mysql
    mysql-connector-java
    ${mysql.version}

    3, In database testdb:

    DROP TABLE IF EXISTS `person`;
    CREATE TABLE `person` (
    `Id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL,
    `country` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`Id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

    1. makarovd says:

      In linux :
      CREATE TABLE `PERSON` (
      -> `Id` int(11) NOT NULL AUTO_INCREMENT,
      -> `name` varchar(255) DEFAULT NULL,
      -> `country` varchar(255) DEFAULT NULL,
      -> PRIMARY KEY (`Id`)
      -> ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

  64. Keval Soni says:
    @Controller
    public class TravelHelperController {
    	
    	
    	private static Logger log=Logger.getLogger(TravelHelperController.class.getName());
    	
    	
    	private UserProfileService userProfileService;
    	
    	@Autowired(required=true)
    	@Qualifier(value="userProfileService")
    	public void setUserProfileService(UserProfileService profile){
    		this.userProfileService = profile;
    	}
    	
    	@RequestMapping("/welcome")
    	public ModelAndView helloWorld(){
    		System.out.println("In TravelHelperController :: method helloWorld");
    		log.info("In TravelHelperController :: method helloWorld");
    		String message = ""
    				+ "********** Hello second page ";
    		return new ModelAndView("welcome", "message", message);
    	
    	}
    	
    	@RequestMapping("/login")
    	public ModelAndView checkLogin(){
    		System.out.println("In TravelHelperController :: method checkLogin");
    		log.info("In TravelHelperController :: method checkLogin");
    		List profile = userProfileService.listProfile();
    		System.out.println("Size : "+profile.size());
    		return new ModelAndView("home", "message", "in home");
    	}
    	
    }
    

    Error Log:

    Dec 04, 2016 2:04:49 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet 'travelhelper'
    Dec 04, 2016 2:04:50 PM org.apache.catalina.core.ApplicationContext log
    
    SEVERE: StandardWrapper.Throwable
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'travelHelperController': Unsatisfied dependency expressed through method 'setUserProfileService' parameter 0: No qualifying bean of type [com.travelhelper.service.UserProfileService] found for dependency [com.travelhelper.service.UserProfileService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.travelhelper.service.UserProfileService] found for dependency [com.travelhelper.service.UserProfileService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:647)
    

    Kindly help me in resolving this issue

      1. Omar Córdova says:

        How did you fix this problem?

  65. michael says:

    i found a little problem, when i update the person with a error message as follows: org.hibernate.PersistentObjectException: detached entity passed to persist – with JPA.
    it need to change the session.persist(p) to session.update(p) in updatePerson method.

  66. Akouri ammar says:

    I wrote the code from scratch and checked the URLs but still getting 404

  67. Arasu says:

    Hi Pankaj,

    Thanks for your project. But i’m getting error like “org.hibernate.HibernateException: No Session found for current thread” while loading the index page.

    Awaiting for your response.

    1. venu says:

      org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

      I am getting this error

  68. Raja says:

    I downloaded the project and ran it. I am getting 404.

    1. Akouri ammar says:

      Followed all the steps but I still get 404, It must be the paths, Please let me know if you find a solution !

  69. deep says:

    Hi Pankaj

    I used same code as you given.But always shown “HTTP Status 404 – /SpringMVCHibernate/”

  70. Jack says:

    I’ve tried to run this, but I am seeing the following error. Not that I am not using Eclipse, but rather I’m trying to run from a console. Is this something that needs to have Eclipse to be able to run, or can it be done without it?

    INFO: HHH000397: Using ASTQueryTranslatorFactory
    Exception in thread “main” org.hibernate.MappingException: Unknown entity: com.journaldev.model.Person
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1488)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:242)
    at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:521)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:116)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    at com.journaldev.dao.PersonDAOImpl.save(PersonDAOImpl.java:22)
    at com.journaldev.main.SpringHibernateMain.main(SpringHibernateMain.java:22)

    My Classpaths are correct, but I don’t know what I’m missing. Thanks in advance if you have any help to give!

  71. epo says:

    Excelente explicación. Gracias por el soporte.

  72. angel says:

    I don’t know why but when I open localhost:8080/SpringMVCHibernate/persons I do get the view but without any buttons and the query is not executed.

    On the console I get.
    Hibernate: select person0_.id as id1_0_, person0_.country as country2_0_, person0_.name as name3_0_ from table_person person0_

    I’m using MariaDB 10.1.8 because that’s the installed version on my localhost.
    Any ideas?

  73. Abhay says:

    I am using mysql as database.
    I am not able to get more than 10 connections.
    this is my configuration.

    schema.hbm.xml

    org.hibernate.dialect.MySQLDialect
    10
    5
    100
    update

    1. webjb says:

      MySQL allows only 10 connections if you want more you have to kill other process which are running

  74. Ajaykumar says:

    Awesome My friend 🙂 Very nice detailed tutorials with simplified manner.

  75. krishna says:

    can you provide jar files instead of pom.xml and myeclipse structure required instead of eclipse

  76. jayesh p says:

    Superb Pankaj, thanks this really helped me. keep up the good work 🙂

  77. ilker Eker says:

    Great working Example. Thanks 🙂

  78. Eknath Take says:

    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SpringMVCHibernate]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SpringMVCHibernate]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    … 6 more
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@354285fc]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4928)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5058)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 6 more
    Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@5a603673]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:699)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 9 more
    Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.JarResourceSet.initInternal(JarResourceSet.java:96)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    … 12 more
    Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(ZipFile.java:60)
    at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:717)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:419)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    at sun.misc.IOUtils.readFully(IOUtils.java:65)
    at java.util.jar.JarFile.getBytes(JarFile.java:425)
    at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193)
    at java.util.jar.JarFile.getManifest(JarFile.java:180)
    at org.apache.catalina.webresources.JarResourceSet.initInternal(JarResourceSet.java:94)
    … 13 more

    Aug 26, 2016 11:37:54 PM org.apache.catalina.core.ContainerBase startInternal
    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:924)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 6 more

    Aug 26, 2016 11:37:54 PM org.apache.catalina.startup.Catalina start
    SEVERE: The required Server component failed to start so Tomcat is unable to start.
    org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:769)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 7 more
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:441)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 9 more
    Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:924)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 11 more

    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol pause
    INFO: Pausing ProtocolHandler [“http-nio-8080”]
    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol pause
    INFO: Pausing ProtocolHandler [“ajp-nio-8009”]
    Aug 26, 2016 11:37:54 PM org.apache.catalina.core.StandardService stopInternal
    INFO: Stopping service Catalina
    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol destroy
    INFO: Destroying ProtocolHandler [“http-nio-8080”]
    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol destroy
    SEVERE: Failed to destroy end point associated with ProtocolHandler [“http-nio-8080”]
    java.lang.NullPointerException
    at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:305)
    at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:481)
    at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:823)
    at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:533)
    at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:859)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:629)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)

    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol destroy
    INFO: Destroying ProtocolHandler [“ajp-nio-8009”]
    Aug 26, 2016 11:37:54 PM org.apache.coyote.AbstractProtocol destroy
    SEVERE: Failed to destroy end point associated with ProtocolHandler [“ajp-nio-8009”]
    java.lang.NullPointerException
    at org.apache.tomcat.util.net.NioEndpoint.releaseCaches(NioEndpoint.java:305)
    at org.apache.tomcat.util.net.NioEndpoint.unbind(NioEndpoint.java:481)
    at org.apache.tomcat.util.net.AbstractEndpoint.destroy(AbstractEndpoint.java:823)
    at org.apache.coyote.AbstractProtocol.destroy(AbstractProtocol.java:533)
    at org.apache.catalina.connector.Connector.destroyInternal(Connector.java:1023)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:589)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:859)
    at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:305)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:629)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:351)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:485)

  79. Andrew says:

    Got it running with postgres! Thanks for the great tutorial.

  80. Basavanth says:

    when i am trying to hit the url http://localhost:8080/SpringMVCHibernate/persons i am getting following error

    Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    	at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)
    	at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
    	at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
    	at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    	at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    	at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
    	at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
    	at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)
    	at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:429)
    	at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    	at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    	at com.sun.proxy.$Proxy44.listPersons(Unknown Source)
    	at com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    	at java.lang.Thread.run(Thread.java:745)
    Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    	at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)
    	at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
    	at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
    	at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    	at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    	at org.hibernaWARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: null
    ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
    
    1. sooraj says:

      It could be because you have not added the mysql jar or dependency.

  81. arjun says:

    hii i downloaded the example but it only have 1 folder and a pom file. The size of the file is only 50kb.. what might be the problem..

    1. Pankaj says:

      It’s a maven project, build it.

  82. akshay pai says:

    Hi, Excellent article. I actually had a problem with handling Database tables in java Spring which do not have any primary key. For example Mapping tables , usually don’t have any primary key. I took some time to understand how i can go about doing it teh right way. Ive put a small tutorial on it.
    https://sourcedexter.com/2015/09/26/handling-database-tables-with-no-primary-key-in-spring-mvc-and-hibernate/

  83. madhu says:

    I am getting below error,

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    1. michael says:

      try URL

      /SpringMVCHibernate/persons

      1. Martin says:

        I have the same error and adding /persons to the url didn’t work for me either.

  84. yogendra says:

    i m getting mozo failure excetion after the import of this project.i have already change the Jdk Setting of the project but still the problem is same .plz advice me if anyone knows how to resolve this.thanks in advance.

  85. John says:

    Hi Pankaj,
    I downloaded the final project, but don’t know how to run it.
    Could you please write something step by step to show how to work with the project?
    I am a newbie, but I feel your tutorial is really good. Thank you.

    1. Pankaj says:

      Just follow the steps in the tutorial. There will be a SQL script to create database tables, just build and deploy into Tomcat and run it. Check for database connection settings and make sure to have Database driver jar in either your application or inside tomcat lib directory.

      1. Someone says:

        It just doesn’t work. I compiled it, set the mysql credential, put things (hibernate) to build path, but it doesn’t work. In my IDE (STS) It compiles, but front page give 404 error, and persons/ gives HTTP error 500.

  86. Dawid says:

    Works great, but have one question.

    My hibernate configuration is not doing anything with the Person.java

    Even if I add some column, it will not create it in my database. I’ve added

    org.hibernate.dialect.MySQL5InnoDBDialect
    true
    create-drop

    But didn’t help.

    Anything to force hibernate to rebuild the whole table.

    Help.

  87. Subrato B says:

    Hi Pankaj,

    Could you help me on this.

    I am using Java 7 and JBoss 7, But I am facing following error when I start server.

    20:40:24,004 ERROR [org.springframework.web.servlet.DispatcherServlet] (MSC service thread 1-7) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) [spring-context-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) [spring-context-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) [spring-webmvc-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at javax.servlet.GenericServlet.init(GenericServlet.java:242) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
    	at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1202) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1102) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3655) [jbossweb-7.0.13.Final.jar:]
    	at org.apache.catalina.core.StandardContext.start(StandardContext.java:3873) [jbossweb-7.0.13.Final.jar:]
    	at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    	at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
    	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.7.0_80]
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.7.0_80]
    	at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_80]
    Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
    	at org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:936) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:824) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
    	at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) [spring-beans-4.0.3.RELEASE.jar:4.0.3.RELEASE]
    	... 26 more
    
    1. Pankaj says:

      Check your application jar files, NoSuchMethod error comes when jars are not compatible. Your code is trying to call a method, but the class loaded doesn’t have that.

  88. Peter steve says:

    Hi,
    I download the source and build in eclipse and not problem.
    When i run with tomcat i get a exception with personDAO.
    I sent to you a email with the exactly problem and too the source code of application.
    Please, help me to fix the problem.

  89. Peter Steve says:

    Hi,
    i have this error above. I see other persons have the same problem.

    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.service.PersonServiceImpl] for bean with name ‘personService’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.service.PersonServiceImpl

    Finally, what is the solution to problem?
    I sent to you a email with the code
    Please help me to fix the problem
    Thanks very much

  90. tanship says:

    Thank you for fresh good example!!

  91. ben26 says:

    Hi,

    could anyone make a video tutorial on how to get this application work with the Intellij IDEA IDE? I’m kind of a newbie and having some troubles there.
    Help would really be appreciated 🙂

    Thanks!

  92. BALAKUMARAN R says:

    please can u tell me , what this error is shown

    Jun 21, 2016 6:40:56 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:SpringMVCHibernate' did not find a matching property.
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server version:        Apache Tomcat/7.0.64
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server built:          Aug 19 2015 17:18:06 UTC
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server number:         7.0.64.0
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Name:               Windows NT (unknown)
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Version:            6.2
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Architecture:          x86
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Java Home:             C:\Program Files (x86)\Java\jdk1.7.0_01\jre
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Version:           1.7.0_01-b08
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Vendor:            Oracle Corporation
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_BASE:         F:\Search\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_HOME:         F:\apache-tomcat-7.0.64
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:56995
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.base=F:\Search\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.home=F:\apache-tomcat-7.0.64
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dwtp.deploy=F:\Search\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Djava.endorsed.dirs=F:\apache-tomcat-7.0.64\endorsed
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dfile.encoding=Cp1252
    Jun 21, 2016 6:40:56 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
    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 Files (x86)\Java\jdk1.7.0_01\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Java\jdk1.7.0_01\jre\bin;C:/Program Files (x86)/Java/jre7/bin/client;C:/Program Files (x86)/Java/jre7/bin;C:/Program Files (x86)/Java/jre7/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Common Files\lenovo\easyplussdk\bin;C:\Program Files (x86)\Skype\Phone\;F:\eclipse;;.
    Jun 21, 2016 6:40:56 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8080"]
    Jun 21, 2016 6:40:56 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
    Jun 21, 2016 6:40:56 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 500 ms
    Jun 21, 2016 6:40:56 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    Jun 21, 2016 6:40:56 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.64
    Jun 21, 2016 6:40:57 PM org.apache.catalina.startup.TldConfig execute
    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    Jun 21, 2016 6:40:57 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    Jun 21, 2016 6:40:57 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.
    Jun 21, 2016 6:40:58 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.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/spring/root-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 39; Premature end of file.
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    	at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    	at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    	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:1110)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    	at java.lang.Thread.run(Thread.java:722)
    Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 39; Premature end of file.
    	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
    	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
    	at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
    	at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
    	at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1375)
    	at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1016)
    	at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
    	at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
    	at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
    	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
    	at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
    	at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
    	at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:240)
    	at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:300)
    	at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:428)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
    	... 23 more
    
    Jun 21, 2016 6:40:58 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
    Jun 21, 2016 6:40:58 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/SpringMVCHibernate] startup failed due to previous errors
    Jun 21, 2016 6:40:58 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    Jun 21, 2016 6:40:58 PM org.apache.catalina.core.StandardContext listenerStop
    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
    	at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
    	at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:921)
    	at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:895)
    	at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:841)
    	at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:579)
    	at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:115)
    	at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:5050)
    	at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5712)
    	at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    	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:1110)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    	at java.lang.Thread.run(Thread.java:722)
    
    Jun 21, 2016 6:40:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8080"]
    Jun 21, 2016 6:40:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Jun 21, 2016 6:40:58 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1630 ms
    
    1. Abhinav says:

      @BALAKUMARAN : Your root-context.xml file is empty & missing xmlns. Please download the project and copy the file from it. I was also facing the same error.

      1. Swastik Vn says:

        root-context.xml file is empty in this example. so it is giving file not found exception to me.

    2. naveen says:

      u have miss configuration of the disptcuter-servlet.xml Spring versions and xsd files are missed

  93. gautham says:

    hi its a great tutorial , can you make a tutorial for spring mvc curd using one-to-one mapping. it will be of great help .

  94. Alexander says:

    Just want to say thank you for sharing this great tutorial!

    1. Pankaj says:

      you are welcome Alexander

    2. armel says:

      Hi Pankaj,
      I just wanted to say thanks for this tutorial it’s awesome

  95. Newbie says:

    Really Really works !
    Many Thanksssss !!!!! I had searched for the tutorial for a month, but only this tutorial works for me
    Thank You for this awesome tutorial !
    I hope u can teach more and more .
    Thank You !

    1. Pankaj says:

      Thanks for the awesome comment, it made my day. 🙂

  96. Sudipto says:

    Hi Pankaj,

    I have been following this tutorial on Spring MVC . Your tutorial is a great source of learning.
    I have one doubt . If I have more than one DAO/ Service class , how do I mention in servlet-context.xml ?

    Thanks a lot for making such a great tutorial. Keep up the good work.

    1. Pankaj says:

      You can have multiple DAO and Service classes. Just define them in spring bean configuration file or use Spring annotations.

  97. Denis says:

    Hi Pankaj,

    I’m getting error:
    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    I am using pivotal server v3.1.

    Please help.

    Thanks,
    Denis.

    1. Pankaj says:

      Check the servlet context of your war file and the correct URI.

  98. Shudhanshu Verma says:

    Great work mate!! thank you so much

    1. Pankaj says:

      Thanks Sudhanshu.

  99. Mohd Umar says:

    Thank you for such a nice and easy tutorial.

    A quick note, for those who getting Could not connect
    add these dependency in your pom.xml

    mysql
    mysql-connector-java
    5.1.17
    jar
    compile

    1. Pankaj says:

      I have already added a note for this.

    2. ilker Eker says:

      You are great my friend. You have solved the problem 🙂

  100. Ravan says:

    Thanks for your tutorial. It really helps beginners to understand both Spring and Hibernate Concepts at one time.

    1. Pankaj says:

      Thanks for the nice words buddy.

  101. gadziki says:

    IT DOESNT WORK !!

    1. Pankaj says:

      Please let me know what error you are getting. Common errors you might get are:

      1. Wrong URL – 404 error means something wrong in URL.
      2. Database connection issue – check for MySQL driver, user password etc.

      1. Abhishek Mishra says:

        I am getting error 4 url not found please suggest how to get the solution for this.

  102. Shivanshu says:

    Great work , keep it up.

    1. Pankaj says:

      Thanks Shivanshu for kind words.

  103. MeenaKannan says:

    It looks good and also works well . Thanks

    1. Pankaj says:

      Thanks Meena for the nice comment.

  104. Raul says:

    Here is the mysql connector for java pom dependency for all of those who are having problems.

    mysql
    mysql-connector-java
    5.1.17

    1. Pankaj says:

      I have mentioned it clearly that I have MySQL driver in tomcat lib directory, so I don’t need to include that. It’s a very simple fix and can be easily found by looking at logs for error.

  105. svorobei says:

    Dear Pankaj, please tell me what went wrong? i have include msql-connector to pom, changed both login and pass, created db “testdb”, but i’m getting these errors and exceptions: (i’m using idea)

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    root cause
    
    org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
    	org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:515)
    	org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    	org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    	org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    	org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    	com.sun.proxy.$Proxy117.listPersons(Unknown Source)
    	com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	java.lang.reflect.Method.invoke(Method.java:497)
    	org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    root cause
    
    org.hibernate.exception.GenericJDBCException: Could not open connection
    	org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    	org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    	org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
    	org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)
    	org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:429)
    	org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    	org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    	org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    	org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    	com.sun.proxy.$Proxy117.listPersons(Unknown Source)
    	com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	java.lang.reflect.Method.invoke(Method.java:497)
    	org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    root cause
    
    java.sql.SQLException: The server time zone value '���������� ����� (����)' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:695)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:663)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:653)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:638)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:606)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:624)
    	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:620)
    	com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:68)
    	com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1683)
    	com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:656)
    	com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:349)
    	com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221)
    	java.sql.DriverManager.getConnection(DriverManager.java:664)
    	java.sql.DriverManager.getConnection(DriverManager.java:208)
    	org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
    	org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
    	org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
    	org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
    	org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    	org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
    	org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)
    	org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:429)
    	org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    	org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    	org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    	org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    	com.sun.proxy.$Proxy117.listPersons(Unknown Source)
    	com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	java.lang.reflect.Method.invoke(Method.java:497)
    	org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    root cause
    
    com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value '���������� ����� (����)' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    	sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    	sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    	java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    	com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
    	com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73)
    	com.mysql.cj.jdbc.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:118)
    	com.mysql.cj.mysqla.MysqlaSession.configureTimezone(MysqlaSession.java:308)
    	com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2474)
    	com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1817)
    	com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1673)
    	com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:656)
    	com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:349)
    	com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221)
    	java.sql.DriverManager.getConnection(DriverManager.java:664)
    	java.sql.DriverManager.getConnection(DriverManager.java:208)
    	org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
    	org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
    	org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
    	org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
    	org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    	org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
    	org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
    	org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)
    	org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:429)
    	org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
    	org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
    	org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    	org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    	org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    	com.sun.proxy.$Proxy117.listPersons(Unknown Source)
    	com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	java.lang.reflect.Method.invoke(Method.java:497)
    	org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    
    1. Pankaj says:

      Do one thing, write a standalone java class and check if you are able to connect using JDBC API?

  106. Siva says:

    Thanks my friend.your article is very great helpful.

    1. Pankaj says:

      Appreciate your comment buddy. These type of comments help me keep going.

  107. dous says:

    hi,

    thanks for great tutorial. i used it to write my own application. however i see one error up there.

    add person method on person controller class returns null pointer exception on if clause because of == 0 check. i resolved it with == null clause. changing part here below.

    //For add and update person both
    @RequestMapping(value= “/person/add”, method = RequestMethod.POST)
    public String addPerson(@ModelAttribute(“person”) Person p){

    // if(p.getId() == 0){ –> changed it
    if(p.getId() == null){
    //new person, add it
    this.personService.addPerson(p);

    1. Pankaj says:

      You must be using ID as String. For my example id is “int”, so it will have default value as 0. 🙂

  108. Marat says:

    Hi Pankaj,

    Very nice Example )))

    You will not prompt me how to configure JNDI in Spring Bean Configuration Context(Servlet-Context) for AS WildFly

    Thanks

    1. Pankaj says:

      I am not sure what you are asking but thanks for appreciating. 🙂

  109. trong says:

    i installed is ok. but add and config more . Plz view youtube and note thanks in youtube if you feel ok.
    😉
    https://youtu.be/ndSbbqEzJaw

    1. Pankaj says:

      Thanks for making the video. I wish you had put audio too. Also put details about the issue and steps for solution here.

  110. DC says:

    How can we do edit without logger

    1. Pankaj says:

      Not sure what you are looking for.

  111. DC says:

    Nice Example…
    But how can we edit the details without using logger

    1. Pankaj says:

      Loggers are not editing anything, that is just to log the messages to check and confirm that things are working fine.

  112. don says:

    hello, dao file and model file use which tool(version) to generate? thanks

    1. Pankaj says:

      i have created it myself, but you can use some tools to do it. Check if there is some option in Hibernate Tool Eclipse plugin? You can read below article for a quick roundup on Hibernate Tools Eclipse plugin.

      https://www.journaldev.com/2940/hibernate-tools-eclipse-plugin-for-generating-hibernate-mapping-and-configuration-files

  113. Venkatesh Manohar says:

    Thanks a lot. It really helped me a lot to start a Spring Hibernate project from scratch.

    1. Pankaj says:

      You are welcome Venkatesh.

  114. eksa says:

    hi pankaj,

    for some reason the app does the job but nothing happens in the database(add person)?!

    1. Pankaj says:

      check your logs and see if you are committing the transaction.

  115. Anand says:

    Thanks Pankaj, It worked like a charm 🙂

    1. Pankaj says:

      Awesome Anand, glad to hear.

  116. Ramkumar says:

    i am getting this (No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’) error

    1. sherif says:

      same with me , if you did it please tell me how

      1. Pankaj says:

        Check the images for correct URI, also check the request mapping configured.

  117. Ramkumar says:

    i am trying to import this project but i am getting No projects are found to import?

    1. Pankaj says:

      its a maven based project, check you are at the right directory or not. You need to use the root directory while importing maven project, so that Eclipse will scan the pom.xml file.

  118. amit says:

    I am getting (No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’) on console…could any one help me
    thanks

    1. DC says:

      instead of your url just write URl /SpringMVCHiberante/persons

      1. Pankaj says:

        Thanks for helping Amit. Appreciate it.

  119. abinagabalan says:

    how to add multiple internal resource view resolver

    1. Pankaj says:

      I have not tried it, you can check if there is some settings for that in InternalResourceViewResolver class?

      I have not tried this but I can think you can define multiple InternalResourceViewResolver beans in the spring configuration file, try that and let me know if it works? 🙂

  120. abinagabalan says:

    Above spring and hibernate integration code has worked for me. Thanks for providing ariticial

    1. Pankaj says:

      you are welcome buddy.

  121. andy says:

    What is the sense of using Apache Commons DBCP dependecie for connection pooling if Tomcat itself using it? Here is from tomcat documentation:
    “NOTE – The default data source support in Tomcat is based on the DBCP connection
    pool from the Commons project. However, it is possible to use any other connection
    pool that implements javax.sql.DataSource, by writing your
    own custom resource factory”

    1. Pankaj says:

      It’s for keeping the things simple, in real life projects you will use Tomcat Data Source for connection pooling.

  122. andy says:

    Why are you using new Integer(id) instead of just using id here:
    Person p = (Person) session.load(Person.class, new Integer(id));

    1. Pankaj says:

      No significance, we can pass “int” also that will be changed to Integer class using autoboxing.

  123. Denis says:

    Hi,

    I tried setting up a simple example based on your in STS3.7.2 using the New->Spring Legacy->Spring MVC and I added your database entries in the servlet-context.xml.

    However, I am getting “Build path is incomplete. Cannot find class file for org/springwork/context/event/EventListenerFactory”

    Would you be able to tell me why?

    Thank you,
    Denis

    com.journaldev.spring.model.Person

    org.hibernate.dialect.MySQLDialect

    true

    1. Pankaj says:

      compare your pom.xml dependencies with mine, you might be missing some artifacts.

  124. Roberto Eder Weiss Juárez says:

    Thanks very much!! You are amazing!!

    1. Pankaj says:

      You are awesome too for taking time in writing this nice comment. 🙂

  125. Mark says:

    In the DAOImpl methods, why does one need to cast to (Person) when the information is coming back from the database/session? What is it passed as?

    1. Pankaj says:

      Because the Hibernate Session load() method returns Object, so we need to explicitly cast it.

  126. Arun MC says:

    Hello Team,

    You have to add below mentioned jar dependency in pom.xml to auto download
    mysql jar

    mysql
    mysql-connector-java
    5.1.6

    Back to basic.
    Yours Arun MC

    1. Pankaj says:

      Thanks Arun. I have this jar in tomcat bin directory, so it was not there in pom.xml

      Since many users are facing this issue, I have added a note in the post for this.

  127. anoop says:

    hi,
    What if I just want to CRUD operation on name? where I need to do changes

    1. Pankaj says:

      Just change the name value, so that only name will be updated. 🙂

  128. Ankit says:

    This is amazing tutorial. Worked perfectly for me after adding mysql-connector-java-5.1.30 in pom.xml.
    One question, I didn’t understand why we didn’t use spring-dispatcher-servlet.xml file. What is the difference between spring-dispatcher-servlet.xml and appServlet/servlet-context.xml

    1. Rahul Survase says:

      both are same. if you have appServlet/servlet-context then you dont need spring-dispatcher-servlet. it creates automatic for maven project.

      1. Pankaj says:

        Thanks for the clarification Rahul, you are absolutely correct. We can keep any name and configure it.

  129. Vibrant says:

    The application is working fine for me. Thank you very much for providing detailed information.

    1. Rajan says:

      Hi Vibrant- Could please send me the code on below email Id ?

      me.rajandayma@gmail.com

      1. Pankaj says:

        You can download the project from the link at the end of article. 🙂

  130. Afjal Ali says:

    Hi all,

    i am geting linkage error with wildFly JBoss 9 so any one help me to solve this problem.

    INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
    17:50:30,042 WARN  [org.jboss.modules] (ServerService Thread Pool -- 22) Failed to define class org.springframework.transaction.event.TransactionalEventListenerFactory in Module "deployment.paytmkyc_war_exploded.war:main" from Service Module Loader: java.lang.LinkageError: Failed to link org/springframework/transaction/event/TransactionalEventListenerFactory (Module "deployment.paytmkyc_war_exploded.war:main" from Service Module Loader)
    	at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:437)
    	at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:269)
    	at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:77)
    	at org.jboss.modules.Module.loadModuleClass(Module.java:560)
    	at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:197)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
    	at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
    	at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
    	at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.registerTransactionalEventListenerFactory(AnnotationDrivenBeanDefinitionParser.java:92)
    	at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parse(AnnotationDrivenBeanDefinitionParser.java:60)
    	at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
    	at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1411)
    	at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1401)
    	at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:168)
    	at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
    	at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    	at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    	at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    	at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
    	at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    	at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    	at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    	at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    	at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    	at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    	at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    	at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
    	at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
    	at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
    	at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:230)
    	at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:131)
    	at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:511)
    	at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
    	at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    	at java.lang.Thread.run(Thread.java:745)
    	at org.jboss.threads.JBossThread.run(JBossThread.java:320)
    Caused by: java.lang.NoClassDefFoundError: org/springframework/context/event/EventListenerFactory
    	at java.lang.ClassLoader.defineClass1(Native Method)
    	at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    	at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:353)
    	at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:432)
    	... 49 more
    
    1. Pankaj says:

      Caused by: java.lang.NoClassDefFoundError: org/springframework/context/event/EventListenerFactory

      Seems like you are missing some jar files.

  131. Fine to me. I implement wiht oracle 11g

    I made a maven for oracle jar library ojdbc6.jar

    com.oracle
    ojdbc6
    11.2.0.3.0

    1. Pankaj says:

      That’s the beauty of hibernate, just change some configs and you are able to switch database vendor. Loosely coupled from database point of view.

  132. Sergey says:

    Thank you very much for the example, but it does not work. After the deploying on my server I have something like this:

    HTTP Status 404 –

    type: Status report

    message

    description: The requested resource is not available.

    Apache Tomcat/8.0.28

    1. Pankaj says:

      Please check the URIs.

  133. Arjun says:
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registrationDao' defined in ServletContext resource [/WEB-INF/MyHotelServlet-servlet.xml]: Cannot resolve reference to bean 'hibernate4AnnotatedSessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/MyHotelServlet-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.orm.hibernate4.LocalSessionFactoryBuilder
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1145)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1069)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:616)
    	org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    	org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    	org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    	org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    	org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    	org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    	org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    	javax.servlet.GenericServlet.init(GenericServlet.java:158)
    	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    	org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    	org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    	org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    	java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    	java.lang.Thread.run(Unknown Source)
    
    
    root cause 
    
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/MyHotelServlet-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.orm.hibernate4.LocalSessionFactoryBuilder
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1145)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1069)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:616)
    	org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    	org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    	org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    	org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    	org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    	org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    	org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    	javax.servlet.GenericServlet.init(GenericServlet.java:158)
    	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    	org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    	org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    	org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    	java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    	java.lang.Thread.run(Unknown Source)
    
    
    root cause 
    
    java.lang.NoClassDefFoundError: Could not initialize class org.springframework.orm.hibernate4.LocalSessionFactoryBuilder
    	org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:343)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1145)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1069)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:616)
    	org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    	org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    	org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    	org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    	org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    	org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    	org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    	org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    	javax.servlet.GenericServlet.init(GenericServlet.java:158)
    	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    	org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    	org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    	org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    	java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    	java.lang.Thread.run(Unknown Source)
    
    

    Help me in this

    1. Pankaj says:

      java.lang.NoClassDefFoundError: Could not initialize class org.springframework.orm.hibernate4.LocalSessionFactoryBuilder

      You are missing some jar files.

  134. Tom says:

    I followed your tutorial step-by-step, except used the names for my personal database table, and I’m getting an error (seems like a couple other people had the same issue with no resolution). Any help would be appreciated.

    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 'userProfileController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.sonepar.spring.webapp.UserProfileController.setUserProfileService(com.sonepar.spring.webapp.service.UserProfileService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sonepar.spring.webapp.service.UserProfileService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    	at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.sonepar.spring.webapp.UserProfileController.setUserProfileService(com.sonepar.spring.webapp.service.UserProfileService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sonepar.spring.webapp.service.UserProfileService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:661)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    	... 22 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sonepar.spring.webapp.service.UserProfileService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:618)
    	... 24 more
    
    1. Pankaj says:

      No Bean definition found, please check your bean configurations.

  135. albert says:

    Thank you, its working for me.
    In model, person, table name is Person instead of PERSON (@Table(name=”PERSON”))

    1. Pankaj says:

      ideally table names should be case insensitive.

  136. Fakher Hakim says:

    Hello
    I’m getting this error when i run the application:
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0’: Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.dao.PersonDAOImpl] for bean with name ‘personDAO’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl
    Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.journaldev.spring.service.PersonServiceImpl] for bean with name ‘personService’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.journaldev.spring.service.PersonServiceImpl …..

    i checked the servlet-context.xml but every thing is OK. what the problem ??

    1. Fakher Hakim says:

      i resolved this problem by deleting the interfaces in package DAO and Service

  137. Rajesh says:

    Awesome Example perfectly working….

    1. dandu says:

      updade,delete,edit,….not working could u tell me what is problem…select is working

      1. Pankaj says:

        check if your database user has required privileges? also what is the error you are getting? did u commit the changes?

  138. nacho says:

    what happens if i want the same thing using two or more tables? i have to do the same twice?

    1. Pankaj says:

      For that we have Spring Transaction Management.

  139. Ilton says:

    Nice tutorial. Thank you very much!

    1. BG says:

      No words enough to thank you Pankaj! Keep going.

  140. guest says:

    Hi Sir Please post a detailed answer for how to set welcome page as most of us are getting 404 error.

    1. Pankaj says:

      Hi, If you are in the stage of learning Spring, Hibernate frameworks then I would think you should know about ServletContext, welcome page, accessing correct URLs etc.

      1. ServletContext or application context – it’s the WAR file name in Tomcat, so if your war file name is test.war, then automatically it’s located at host:port/test

      2. Welcome page can be set in the web.xml file, for example.

      <welcome-file-list>  
         <welcome-file>index.html</welcome-file>
      </welcome-file-list>
      

      3. URLs are already there in the images, just follow them.

      1. Marco says:

        Hello Pankaj, I am following your guardians, even if nn understand English well, however, are really good.
        In SpringMVCHibernate app that I imported on eclipse, after creating the database TestDB and three columns (one I phpMyAdmin).
        When you start the application from queso error in the console:
        WARN: org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/ SpringMVCHibernate /] in DispatcherServlet with name ‘appServlet’ and the browser with url – http: // localhost: 8080 / SpringMVCHibernate / with HTTP Error Status report, null message and descizione The Requested resource is not available.
        Do you know how can I do? Thanks …

        1. Pankaj says:

          What is the WAR file name in your Tomcat server. This is because of servlet context of your application.

          1. Maddy says:

            Can you explain this step. about war files and servlet context of the application…in simpler terms. thanks in advance

        2. gangadhar says:

          Thank you sir

  141. Lucas says:

    Great tutorial, dude. Thanks a lot!

  142. bala says:

    it works for me. Nice article thank u sir .awesome tutorial website

  143. Dair says:

    I imported using maven and run it works perfect. thanks

  144. Adit says:

    hai i couldnt your project.. i have error

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    Why to resolved..?

    Thanks

    1. Carlos Cunarro says:

      This problem is because you should check in pom the property final name (it is referenced by property artifact id). Check this property has same name as folder that Tomcat deploys your application (.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/XXX). After doing this and running maven install and then run on server it should be fixed. And try to access XXX/persons url.

      Hope this helps

  145. Andrew says:

    Thank you for the CRUD example!

    I see you are using hidden form fields to maintain state of non-editable entity fields. Is there any other (recommended) way to create CRUD forms that only partially edit an entity?

    If that entity had, for instance, a BLOB field, it would not pass through the form as a hidden input element and would be lost upon every update, correct? How would you approach creating a form for such an entity?

    Thank you,
    Andrew

  146. Subramanya says:

    Thanks It works. As suggested above, changed the pom to include mysql connector . Created test db.

  147. Sachin says:

    No mapping found for HTTP request with URI [/SpringMvcHibernate/] in DispatcherServlet with name ‘appServlet’

    1. Omunt says:

      I also got the same error, I had to do Maven Install in order to generate correctly the application. If you are using Eclipse you can try as I did, go to the project, right click, run as Maven Install. Once is done, then proceed to run on server.

      Good luck!

  148. Shaikh Hussain says:

    without maven.

  149. Shaikh Hussain says:

    Hello Sir,

    i am new to Spring and Hibernate. I want to integrate Spring 3.0 with Hibernate 3.2. But i do not have any idea how to do that. Sir if and only if possible can you provide me a simple example Spring with Hibernate using MVC architecture with annotation.

    Its humble request sir.

    Thank You.

  150. Raichand Ray says:

    Dear Sir,
    Very Good Tutorial.
    Please modify it to include Date of Birth property.
    Also use primefaces .Those will be very much helpful to newbies

    Thanks
    Raichand Ray

  151. Aabid Husain says:

    Good exposure, but not for spring fresher, a lot of jar files have to be added in project, so i suggest that you have to show an image of jar files in this tutorial, It would be great helpful, Thank you sir.

    1. Pankaj says:

      To avoid adding jars manually, we are using Maven.

  152. shikha srivastava says:

    what is the url to execute this code?

  153. Isaac says:

    Muy buenos post gracias, aprendemos mucho de tu trabajo sigue adelante compartiendo el conocimiento.

  154. Nilesh Vadaliya says:

    Thankss broo…… 🙁

  155. Derek says:

    Regarding the 404 errors that people are encountering, I found that I was hitting a 404 error when I was trying to run tomcat out of Eclipse. When I copy-pasted the project war file to the tomcat webapps folder and then ran tomcat from the command prompt, the web app functioned properly.

    So, my steps are as follows:
    1. Run “mvn clean install” from the command prompt
    2. Navigate to the folder that the war file was created in. In my case it was under the ../SpringMVCHibernate/target folder. The command prompt should say where the war file was created.
    3. Copy-paste this war file to your tomcat webapps folder. In my case I keep it under C:\tools\apache-tomcat-7.0.62\webapps
    4. Run tomcat from the command line. The command is “startup.bat”. This assumes you have the CATALINA_HOME system variable set up properly.

    The web app worked after this. Gave myself a headache trying to figure out what was wrong with my code.

    1. Dev says:

      That was very helpful, what is the URL.. localhost:8080/

  156. Peter says:

    Why do you use @Autowired(required=true) @Qualifier(value=”personService”) , and not PersonServiceImpl ?The personService is not only the interface ?

  157. Ashraf says:

    Thank you Pankaj for this wonderful tutorial.
    I imported the project to eclipse and did all the steps required as Aatif did.
    I got to the index.jsp where it says Click to enter.
    When I click I got the error of 404 resource not available.
    Please note this is the first time I’m trying spring, hibernate.

    Any help will be appreciated.

    Thanks

  158. Ravi Rajput says:

    appServlet
    /

    This gives an error in mapping resource not found plz tell me about this problem

  159. DEVIPRASAD HEGDE says:

    Hi Pankaj

    Great work. Worked perfectly once i added the sql connectoe dependency. Thanks a lot fro your efforts.

    1. Mamatha Gurram says:

      Hi DeviPrasad,
      I used the same exact example, but im getting 404 error when i am running the application. Can you please help me.

      Thanks.
      Mamtha

  160. Mamatha Gurram says:

    Hi Pankaj,
    When i am trying to execute the application its showing 404 error .Can you please help me out with this problem.

    Thanks in Advance,
    Mamtha

  161. Prashant says:

    Another question..How do we know whether DB connected or not , any log messages for this? I am using Oracle 11g.

    Thanks..

    1. Prashant says:

      Hi Pankaj,

      Could you please reply below query.

      1).How do we know whether DB connected or not , any log messages for this? I am using Oracle 11g.
      2)Below Exception

        java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'person' available as request attribute
      	org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
      	org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
      	org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
      	org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
      	org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
      	org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
      	org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
      	org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
      	org.apache.jsp.index_jsp._jspx_meth_form_005flabel_005f1(index_jsp.java:427)
      	org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:180)
      	org.apache.jsp.index_jsp._jspService(index_jsp.java:108)
      	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
      	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
      	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
      	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
      	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
      	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
      
      1. Prashant says:

        Please somebody reply to my above query…

        Thanks.
        Prashant

        1. Omunt says:

          Did you check the dialect in the hibernate4AnnotatedSessionFactory. In the example given the dialect is set to org.hibernate.dialect.MySQLDialect. If you are using Oracle you will need to change it to the corresponding correct dialect. I checked and it seems that this should be org.hibernate.dialect.Oracle9iDialect, taken from here http://stackoverflow.com/questions/4369944/hibernate-dialect-for-oracle-database-11g.

  162. Suraj Singh says:

    Awesome stuff. Thanks bro.

  163. Ankush says:

    Thanks pankaj sir.
    U r doing fantastic job for us.

  164. Venkat says:

    Hi Pankaj,

    You are doing a tremendous job.
    Thanks a lot for all the CONTENT..

    Professional to professional bow from my side.

    Thanks,
    Venkat

  165. Manoj says:

    Hi Pankaj,

    Thanks for above given nice example. But i have one issue, when i try to start the tomcat 6.0 in STS. It gives this below given error:- can u help me for this (I am unable to start the Tomcat)

    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:261)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Caused by: java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
    at org.apache.tomcat.util.digester.Digester.(Digester.java:326)
    at org.apache.catalina.startup.Catalina.createStartDigester(Catalina.java:253)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:474)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:562)
    … 6 more
    Caused by: java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 10 more

    Thanks.

  166. Santosh Sm says:

    Hi Pankaj,

    It was a great article….. 🙂 mysql connector dependency is missing in ur pom.xml ……..

  167. serban says:

    Hi Pankaj,

    I used your example but with two classes(book and review) instead of one (person) and I receive an error (below) if i have @Controlled annotation on both classes. If i delete it from one it works but it says No mapping found for HTTP request with URI [/BookReviewApp/] in DispatcherServlet with name ‘servlet’.

    ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'reviewController' bean method
    public java.lang.String com.bookReview.app.ReviewController.editReview(int,org.springframework.ui.Model)
    to {[/edit/{id}],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'bookController' bean method
    public java.lang.String com.bookReview.app.BookController.editBook(int,org.springframework.ui.Model) mapped.

    Thank you,
    Serban

  168. Osama says:

    Thank you very much, finally I found a working example connecting SpringMVC with Hibernate and Maven

  169. Sachin Parse says:

    Very nice example.

    I am getting this error:

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet with name ‘appServlet’

    Give me solution.

    1. Stefania says:

      you have to call: /SpringMVCHibernate/persons

    2. aayush says:

      servlet
      /

      Try this

      1. aayush says:

        Try this only.
        /

  170. Hernando says:

    Friend’ve noticed that not told web.xml as every application should contain, I can explain why?

  171. Jz says:

    Hey! Thank you so much for this wonderful tutorial. Clear and concise. I will now try to integrate this with AngularJS or BackboneJS! For those people encountering database connection-related exceptions, just add mysql Maven dependency to your pom.xml ( I added version 5.1.32)

    Again. Thank you sir! Cheers from the Philippines!

  172. Anas says:

    Hi Pankaj, I’m using Glassfish and I got this error :

    Error An error has occurred
    Exception while loading the app : java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl

    Please Help !!

  173. someone says:

    Great job my friend, thank you so much !

  174. zodiac says:

    Hello, Pankaj! Can you add Search button to your application? Search button is for searching person by name.

  175. Luna says:

    Thanks a LOOOOT for this tutorial !!! It helped me so much! I tried a lot of others tutorials before, and none of them worked…
    I just added this in the pom.xml :

    mysql
    mysql-connector-java
    5.1.32

    And I modified the credentials in servlet-context.xml, and now everything is fine!!
    I saw in other tutorials that we can use java class instead of xml files for configuration, are you considering this solution for your projects ?
    Thanks again!

  176. Vaibhav Mittal says:

    addPerson function in DAOImpl is not working for me.

    I tried below two different ways and both are working:
    1. Session session = this.sessionFactory.getCurrentSession(); // or openSession()
    session.save(p);
    2. Session session = this.sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();
    session.persist(p);
    tx.commit();

    Please check at your end and change code in above DAO accordingly. It will help others.

  177. abhay deva says:

    Nice Article .it’s very simple to understand to spring mvc flow.
    Thank you Pankaj.

    1. Naveen says:

      This is realy good to undersstand spring MVC Web Flow. Thanks Pankaj

  178. Srikanth Vengala says:

    Hi Pankaj, when I run your application locally, I got this exception

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/aop/config/AopNamespaceUtils
    	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
    
  179. Arnaldo Vicente says:

    I need understand how to integrate : Hibernate , Spring MVC with MySQL in NetBeans. Is urgent, if someone have solution code, please send me.

  180. Purba says:

    Hi Pankaj,

    It is nice and concise article. Can you please explain about the client side validation i.e JavaScript integration with Spring MVC?

  181. Andrew says:

    Empty root-context.xml was a source of errors, I’ve changed path in web.xml to “/WEB-INF/spring/appServlet/servlet-context.xml”.

    Also had a problem with deploying using Eclipse(number of jars should be added to classpath manually), so deploy manually or use maven.

    Last problem was that pom.xml doesn’t have a dependency for mysql jdbc driver.

    1. Barstu says:

      Thank you very much 🙂 It works now.

  182. Gururaj says:

    Too many ads.. I am feeling lite bet uncomfortable.
    Many thanks! Clear and concise and works well!

  183. Jarek says:

    sty 22, 2015 12:43:32 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log
    plz look into this

    INFO: Initializing Spring root WebApplicationContext
    sty 22, 2015 12:43:34 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet ‘appServlet’
    sty 22, 2015 12:45:15 PM org.apache.catalina.core.ApplicationContext log
    INFO: Destroying Spring FrameworkServlet ‘spring’
    sty 22, 2015 12:45:16 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    sty 22, 2015 12:45:16 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet ‘spring’

  184. Vikash says:

    Hi,

    It is working in tomcat/webapps installation but not on Eclipse.
    In eclipse it doesnt give the below logs, that is the reason it is not starting up. Anyone any guess why??

    Jan 13, 2015 10:37:55 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    INFO : org.springframework.web.context.ContextLoader – Root WebApplicationContext: initialization started

    Also can anybody explain here how sessionFactory.getCurrentSession() is working in this application. No session was opened in it.

    Many many thanks in Advance . .

  185. Abiy says:

    Many thanks! Clear and concise and works well!

  186. Ty says:

    Hello,

    Where did you download the hibernate and sfl4j jars. The package’s dont match. I cant find one that does.

    Thank You

  187. Herry says:

    Hello Pankaj,

    I’ve tried your code and seem it doesnt work for me.

    There is error code, you can see it in the following : https://www.scribd.com/doc/252024844/Error

    Currently I’m using Netbeans 8.0.1, Apache Tomcat 8.0.9.0, what should I do?

    Thanks..

    Regards,
    Herry

  188. chetan choudhary says:

    Hi,

    I downloaded your code and imported it in my spring tool suite

    Aim: what i am trying to do:
    1. create a spring mvc project in STS by the ready made default template
    2. trying Integrate hibernate with it so that i can integrate hibernate by my self without copying any ready made projects

    Problem faced:

    As per your pom file i have included the two hibernate dependencies, 1 apache dbcp dependency, 1 spring orm dependency

    Now when i try to use annotations like @entity i get error because the javax.persistance is not present in my project.

    in your downloaded project there is hibernate-jpa-2.1-api-1.0.0.Final-sources.jar in your maven dependencies library but not in pom file.

    Did you add it externally? if yes then why not included in pom.

    Please explain the significance of all jars in downloaded project and dependencies in pom and why some jars are present in maven dependencies but not in pom.xml

  189. kailas says:

    I have download this project and deployed it on Apache tomcat. It’s run perfectly but my question is that no need to add mysql-connector-java jar.
    Please answer me. Is there any support in any jar file which you had used in this demo?

    1. Pankaj says:

      Oviously it’s needed for creating MySQLDB connection, i have this jar in server lib. So i dont need that in the project.

  190. Hamid says:

    DOESN’T FUNCTION. waste of time!!!

    1. Hamid says:

      with some changes, which i don’t understand, it functioned. thanks anyway!!

      1. srinivasulu says:

        Oct 04, 2019 3:59:15 PM org.apache.catalina.startup.Catalina start
        INFO: Server startup in 85420 ms
        Oct 04, 2019 4:00:07 PM org.hibernate.engine.internal.StatisticalLoggingSessionEventListener end
        INFO: Session Metrics {
        212238 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        0 nanoseconds spent preparing 0 JDBC statements;
        0 nanoseconds spent executing 0 JDBC statements;
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
        }
        Oct 04, 2019 4:00:07 PM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet [appServlet] in context with path [/SpringMVCHibernate] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.UnsupportedOperationException: Not supported by BasicDataSource] with root cause
        java.lang.UnsupportedOperationException: Not supported by BasicDataSource
        at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1062)
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
        at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
        at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)
        at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
        at com.sun.proxy.$Proxy28.listPersons(Unknown Source)
        at com.journaldev.spring.PersonController.listPersons(PersonController.java:29)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Unknown Source)

  191. Shalom says:

    Hi,
    I am newbie in spring, maven so sorry fir this basic question
    I try to implement your solution but in my context.xml I got this error:

    No setter found for property ‘sessionFactory’ in class … when I define the DAO bean.
    Same error with the service.
    here a part of my context.xml
    The little difference is that I externalized my DAO into a jar.

    com.domitik.domitikCDB.model.Box

    org.hibernate.dialect.MySQL5Dialect
    true

    the

    When I try to run my application I got this exception:
    8:50:54.309 [localhost-startStop-1] ERROR o.s.web.context.ContextLoader – Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘boxControllers’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.domitik.DomitikWS.services.BoxService com.domitik.DomitikWS.controllers.BoxControllers.boxService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.domitik.DomitikWS.services.BoxService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPost…

    Thanks for your help

    1. Shalom says:

      Sorry some context.xml was truncated…

      com.domitik.domitikCDB.model.Box

      org.hibernate.dialect.MySQL5Dialect
      true

      the

  192. Daniel says:

    You software does not respond anything, I have had a problem with error 404.

    tomcat não acusa erro, mas não existe retorno da pagina jsp.

    1. Daniel says:

      tomcat does not accuse error, but there is no return of the jsp page.

  193. Rikenson says:

    What is the content of root-context.xml

  194. Den says:

    Thank you very much for tutorial. Almost all right! But when I start progect, i have an error 404
    No mapping found for HTTP request with URI [/SpringMVCHibernate/] in DispatcherServlet, if I write by hands address /persons all is work! where I need to look. (In servlet-context.xml i change nothing ).

    1. Den says:

      Waiting for youre answer

      1. Pankaj says:

        Sorry for late response, you need to understand URI. Since there is no home page defined, you get error if you go to web application home page. If you don’t want, just put index.html or any other welcome-page in web.xml to avoid this.

        1. Hero says:

          How can be remove 404 error in detailed steps…

    2. vaibhav says:

      Hi guys,

      I got the error in eclipse :
      org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’

      please help me how can resolve this problem.

      Thanks

  195. Rohit says:

    hi Pankaj,

    Thanks for the wonderful tutorials!

    I tried writing a SpringMVC-Hibernate application following this tutorial. Everything goes fine but i get an exception
    org.hibernate.HibernateException: No Session found for current thread
    when i try to do
    Session session = this.sessionFactory.getCurrentSession(); in DAOImpl class
    Execution goes fine without any exception if I replace it with
    Session session = this.sessionFactory.openSession();

    I see we are not creating any session in the tutorial. How are we getting a session?
    Please explain.

    thanks in advance.

    -Rohit

    1. Pankaj says:

      We are getting the session from Spring ORM, as configured below.

      <beans:bean id=”hibernate4AnnotatedSessionFactory”
      class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>

      Check this class source and you might find something causing the issue.

      What are the hibernate properties you are passing, is there any property named “thread”? Try removing that and check again.

  196. Suraj says:

    When I do a maven build , I get the error :Fatal error compiling: tools.jar not found

    Plz help

    1. Omunt says:

      I got the same problem also, it’s because your eclipse is pointing to a JRE Java version not a JDK. http://stackoverflow.com/questions/25185634/maven-build-failed-fatal-error-compiling-tools-jar-not-found

  197. Hemanth says:

    Hi pankaj,

    To fix below error i added below dependency

    org.hibernate.javax.persistence
    hibernate-jpa-2.1-api
    1.0.0.Draft-6

    But still getting the same error
    Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;

    Please help.

    1. Pankaj says:

      What is your java version. The issue seems to be with incompatible versions.

      1. Mitesh Manani says:

        Your Application Server is using JPA version 2.0 whereas you have built your application with JPA version 2.1. Thanks the problem.

      2. Hemanth says:

        Hi Pankaj,

        It’s java version 1.7

        1. Hemanth says:

          Hi Pankaj,

          I am using java version 1.7

          Please help

    2. vadym says:

      in pom

      4.2.8.Final
      or earlier

  198. Hemanth says:

    Hi pankaj,

    I am getting the below error

    Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;

    Please help.

  199. Sergey says:

    Hi, Pankaj.

    Awesome tutorial, helps me a lot, but could you please explain one thing.
    Why should we have “PersonService” interface, that in turn is exact copy of “PersonDAO”?
    Why can’t we just have “PersonServiceImpl” (with better name — “PersonService”). We already provide the layer of data access (“PersonDAO” and “PersonDAOImpl”), so why we need to create another redundant interface if we could use one class (in your case “PersonServiceImpl”) that can invoke interface methods?

    I hope, I’ve explained my point to you

  200. Vipul says:

    I am getting following error, Pls anyone help me to resolve this..

    org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 14 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 23; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘annotation-driven’.

    1. Vipul says:

      And one more exception i have faced at the time of starting tomcat server..

      org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 18 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 64; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘resources’.

  201. Bikash says:

    Hi Pankaj, what is need of root-context.xml?

  202. Abhi says:

    How about an example of Select queries with join conditions and more tables involved? basically a real time example would be ideal

    thanks in advance

  203. fix says:

    create
    Why it not work?
    Hbiernate not create a table (((
    Work only by using sql script.

    1. Manjula says:

      hi Fix,

      I got the same problem.

      You should add the following line to the hibernate properties in the Spring configuration(xml) file.

      create

  204. Priya says:

    Pankaj, thanks for a wonderful and well explained article.

    Is there a way we can have a query which can get us a Person using name field and using the same DAO method structure ??

  205. Sagar Mali says:

    Hi Pankaj,

    Good Article.

    Suppose here, i have another class “Address” and if i want to implement “one-to-many” relationship here with person has multiple addresses. Mean while adding person, i want to add multiple addresses on above html form , so please help me to implement changes in above files.

  206. sandeep k says:

    Hi Pankaj,
    I am looking programmatically and declarative transaction management (for hibernate and spring) example. Can you describe in a blog if one transaction get failed second transaction automatic get reverted.

    Thanks,
    Sandeep

  207. tammy says:

    Hello Pankaj,
    I too am getting the same errors as kernelfreak. Please can you advise us on how to resolve these issues?
    Many thanks.

  208. Marq W says:

    Worked flawlessly for me.

    Thank you very much for taking the time to post this!

    Marq

  209. Alex says:

    Thanks for doing this tutorial. I’d agree with Murali’s suggestion of an extra tutorial, showing changes to the controller and adding a second table to the model.

    Regards
    Alex

  210. Gopalkrishna says:

    Hi,

    Pankaj

    i was facing problem even after changing all requirements like username and password created same database as u given in above example error is.
    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: Could not open connection.

    please help me as soon as possible.

    Thanks and Regards
    Gopalkrishna

    1. Pankaj says:

      You need to include the database driver, I have updated the post with this detail. You could also see the below comment from Aatif for the same.

  211. Aatif says:

    I downloaded the project and successfully ran it after making a couple of bellow changes –

    1. Import project in eclipse. (Any, i used eclipse)
    2. Include MySql connector dependency in pom.xml file as it is missing there.

    mysql
    mysql-connector-java
    5.1.32

    3. Update Project Dependencies – RightClick On Project –> Maven –> Update
    3. Change username and password properties in servlet-context.xml file according to yours.
    4. Create DB with ‘testdb’ name.
    5. Clean, compile and Install project by running bellow maven commands on the console.
    mvn clean compile, mvn install.
    6. Run the project on tomcat server (You can use other server also but i have used tomcat.)
    7. Application is ready at URL – http://localhost:8080/SpringMVCHibernate/persons Cheers.!! 🙂

    1. Pankaj says:

      Hi Aatif,

      Thanks for the detailed comment, I missed adding MySQL Driver jar in project pom.xml file because it’s part of my Tomcat lib directory. In most of the real life scenarios, we use JNDI DataSource configured in the container and for that we need to have driver jars in the container lib directory.

      I hope it clarifies the confusion for anyone else facing the similar issue, i will keep it in mind for future tutorials and include jars in pom.xml dependencies.

    2. Sandeep says:

      Hello Aatif
      I did everything that you said but still I am getting
      WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’

  212. Lokesh Kumar says:

    I’m run this program on NetBeans IDE 8.0 , Whenever run this program problem is occuring like this:

    Severe: Exception while loading the app
    Severe: Undeployment failed for context /EMD
    Severe: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jindal.emd.model.Person] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.web.bind.annotation.ModelAttribute(value=person)}

  213. Rizwan Mursaleen says:

    I think you have forgot to include root-context.xml, if not, How to write root-context.xml

    1. Pankaj says:

      Download the project, for some files where we don’t have anything Spring specific, I might have excluded them.

  214. Santosh Shingare says:

    Hi,Pankaj,

    I am getting this one, when web page is loaded.

    HTTP Status 404 –
    type Status report
    message
    description The requested resource is not available.
    Apache Tomcat/7.0.55

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’

    ************* Web.xml *********************

    contextConfigLocation
    /WEB-INF/spring/root-context.xml

    org.springframework.web.context.ContextLoaderListener

    appServlet
    org.springframework.web.servlet.DispatcherServlet

    contextConfigLocation
    /WEB-INF/spring/appServlet/servlet-context.xml

    1

    appServlet
    /

  215. John Tsun says:

    I got errors when trying to run it:

    org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at
    … …
    Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

    do we need applicationContext.xml file?

  216. Kernelfreak says:

    I am getting the following error when i am using your code in Eclipse.

    java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl

    java.lang.ClassNotFoundException: com.journaldev.spring.service.PersonServiceImpl

  217. happin_boy says:

    how to deploy the project? should I create a new meaven project and move all your files to run? waiting for your response!

    1. Pankaj says:

      Just build the project using Maven command “mvn clean install” or use your IDE to export as WAR file and deploy in the container, here I am using tomcat.

      1. Naveen says:

        I have configured this project in eclipse.For running i am following:
        Run As–>Maven Build ::: clean install

        But build failing with below error:
        “Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project SpringHibernateWeb: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]”
        I have web.xml at required place.
        Can you please advise as what I am missing?

  218. Murali says:

    Hi pankaj,

    can you a post an example to edit multiple records at one shot and save it to database using spring mvc and hibernate.

    1. Pankaj says:

      Why another example, you can extend this one to update multiple records in one go. All you need is small UI changes and Hibernate business logic changes to update multiple records.

  219. chitra says:

    Hi pankaj,

    Can you please help me. i am using the above code but i shows this
    HTTP Status 500 – Servlet.init() for servlet appServlet threw exception and i don’t know why i got this error.

  220. Asis says:

    can u plz draw the flow of the class digram as per the Spring MVC Hibernate MySQL Integration CRUD Example Tutorial ,
    i am not able to understand how each of the calsses are connected to each other mainly service layer
    plz help me asap

    1. micheal says:

      Are you able to execute the above code?

  221. john says:

    please look into this

    ERROR [org.springframework.web.servlet.DispatcherServlet] (MSC service thread 1-4) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate4AnnotatedSessionFactory’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery

    1. Anas says:

      Please help !! I got this error :

      Error An error has occurred
      Exception while loading the app : java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.ClassNotFoundException: com.journaldev.spring.dao.PersonDAOImpl

  222. john says:

    Thanks for your reply pankaj,
    after adding

    in standalone.xml jboss waringin was suppressed but now i have another problem.

    Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate4AnnotatedSessionFactory’ defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;

    i googled and added asm.jar and cglib-nodep-2.1_3.jar but no use.
    please help
    thanks in advance

  223. John says:

    I downloaded the project and deployed on jboss, not able to execute, please help

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages