Spring Hibernate Integration Example Tutorial (Spring 4 + Hibernate 3 and Hibernate 4)

Filed Under: Hibernate

Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. Recently I have written a lot for Spring Tutorial and Hibernate Tutorial, so a post for spring hibernate integration was due for long time.

spring hibernate integration example tutorial

Spring Hibernate

Today in this tutorial, we will use Spring 4 and integrate it with Hibernate 3 and then update the same project to use Hibernate 4. Since there are a lot of versions for Spring and Hibernate both and Spring ORM artifact supports both Hibernate 3 and Hibernate 4, it’s good that I list all the dependencies I have used in my project.

Note that I have noticed that all spring and hibernate versions are not compatible, below versions have worked for me so I think they are compatible. If you are using some other versions and getting java.lang.NoClassDefFoundError, then it means that they are not compatible. Mostly it’s because Hibernate classes are moved from one package to another causing this error. For example org.hibernate.engine.FilterDefinition class is moved to org.hibernate.engine.spi.FilterDefinition in latest hibernate versions.

  • Spring Framework Version: 4.0.3.RELEASE
  • Hibernate Core and Hibernate EntityManager Version: 3.6.9.Final and 4.3.5.Final
  • Spring ORM Version: 4.0.3.RELEASE

Database Setup

I am using MySQL database for my project, so below setup.sql script will create the necessary table for this example.


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=5 DEFAULT CHARSET=utf8;
commit;

Spring Hibernate Integration Example Project Structure

Below image shows the final project structure, we will go through each of the components one by one.

Spring-Hibernate-Integration-Example-Project

Maven Dependencies

We will first look into our pom.xml file for all the required dependencies and their versions.


<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.springframework.samples</groupId>
	<artifactId>SpringHibernateExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>

		<!-- Generic properties -->
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

		<!-- Spring -->
		<spring-framework.version>4.0.3.RELEASE</spring-framework.version>

		<!-- Hibernate / JPA -->
		<!-- <hibernate.version>4.3.5.Final</hibernate.version> -->
		<hibernate.version>3.6.9.Final</hibernate.version>

		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>

	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Spring ORM support -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
	</dependencies>
</project>

Important Dependencies for Spring and Hibernate Integration Project are:

  • spring-context and spring-tx for core Spring functionalities. Notice that I am using version 4.0.3.RELEASE.
  • spring-orm dependency for Spring ORM support, it’s required for hibernate integration in our spring project.
  • hibernate-entitymanager and hibernate-core dependencies for Hibernate framework. Notice that version is 3.6.9.Final, for using Hibernate 4 all we need is to change it to 4.3.5.Final as commented in above pom.xml file.
  • mysql-connector-java for MySQL driver for database connection.

Model Class or Entity Bean

We can use Hibernate XML based mapping as well as JPA annotation based mapping. Here I am using JPA annotations for mapping because hibernate provides JPA implementation.


package com.journaldev.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;
	}
}

DAO Classes

We will implement two methods in our DAO classes, first to save the Person object into table and second that will fetch all the records from the table and returns the list of Persons.


package com.journaldev.dao;

import java.util.List;

import com.journaldev.model.Person;

public interface PersonDAO {

	public void save(Person p);
	
	public List<Person> list();
	
}

Above DAO class implementation would be like below.


package com.journaldev.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.journaldev.model.Person;

public class PersonDAOImpl implements PersonDAO {

	private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
	@Override
	public void save(Person p) {
		Session session = this.sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.persist(p);
		tx.commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> list() {
		Session session = this.sessionFactory.openSession();
		List<Person> personList = session.createQuery("from Person").list();
		session.close();
		return personList;
	}

}

Notice that this is the only place where we are using Hibernate related classes. This pattern makes our implementation flexible and easy to migrate from one technology to another. For example, if we want to use iBatis ORM framework, all we need is to provide a DAO implementation for iBatis and then change the spring bean configuration file.

In above example, I am using Hibernate session transaction management. But we can also use Spring declarative transaction management using @Transactional annotation, read more at Spring Transaction Management.

Spring Bean Configuration File for Hibernate 3 Integration

Let’s first look at the spring bean configurations we need for Hibernate 3 integration, we will look into detail later on.


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

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

<!-- Hibernate 3 XML SessionFactory Bean definition-->
<!-- 	<bean id="hibernate3SessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>person.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
			</value>
		</property>
	</bean> -->

<!-- Hibernate 3 Annotation SessionFactory Bean definition-->
	<bean id="hibernate3AnnotatedSessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.journaldev.model.Person</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.current_session_context_class">thread</prop>
				<prop key="hibernate.show_sql">false</prop>
			</props>
		</property>
	</bean>
	
	<bean id="personDAO" class="com.journaldev.dao.PersonDAOImpl">
		<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
	</bean>
</beans>

There are two ways we can provide database connection details to Hibernate, first by passing everything in hibernateProperties and second by creating a DataSource and then passing it to hibernate. I prefer the second approach, that’s why we have Apache Commons DBCP dependency to create a BasicDataSource by setting database connection properties.

For Spring and Hibernate 3 integration, Spring ORM provides two classes – org.springframework.orm.hibernate3.LocalSessionFactoryBean when hibernate mappings are XML based and org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean for annotations based mapping. I have provided simple bean configuration of LocalSessionFactoryBean in comments, if you are using XML based mappings. AnnotationSessionFactoryBean extends LocalSessionFactoryBean class, so it has all the basic properties for hibernate integration.

The properties are self understood and mostly hibernate related, so I will not go into much detail for them. But if you are wondering from where hibernateProperties, annotatedClasses are coming, you need to look into the bean class source code.

Notice the bean definition of personDAO, like I said earlier if we have to switch to some other ORM framework, we need to change the implementation class here and set any other properties we need.

Spring 4 Hibernate 3 Test Program

Our setup is ready now, let’s write a simple program to test our application.


package com.journaldev.main;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

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

public class SpringHibernateMain {

	public static void main(String[] args) {

		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
		
		PersonDAO personDAO = context.getBean(PersonDAO.class);
		
		Person person = new Person();
		person.setName("Pankaj"); person.setCountry("India");
		
		personDAO.save(person);
		
		System.out.println("Person::"+person);
		
		List<Person> list = personDAO.list();
		
		for(Person p : list){
			System.out.println("Person List::"+p);
		}
		//close resources
		context.close();	
	}
}

When we execute above program, we get a lot of output related to Hibernate because I haven’t setup logging properly, but that’s out of scope of this tutorial. However we get following output generated by our program.


Person::id=3, name=Pankaj, country=India
Person List::id=1, name=Pankaj, country=India
Person List::id=2, name=Pankaj, country=India
Person List::id=3, name=Pankaj, country=India

Spring 4 Hibernate 4 integration changes

Now let’s change our application to use Hibernate 4 instead of Hibernate 3. For this migration, we need to make only following configuration changes.

  1. Change the hibernate version to 4.3.5.Final in the pom.xml file, as shown in comments above.
  2. Change the spring bean configuration file, till now you must have figured out that Spring bean configuration file is the key for integration of spring and hibernate framework. Below spring bean configuration file will work for Spring 4 and Hibernate 4 versions.
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    	xmlns:tx="http://www.springframework.org/schema/tx"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    		destroy-method="close">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
    		<property name="url" value="jdbc:mysql://localhost:3306/TestDB" />
    		<property name="username" value="pankaj" />
    		<property name="password" value="pankaj123" />
    	</bean>
    
    
    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="hibernate4AnnotatedSessionFactory"
    		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="annotatedClasses">
    			<list>
    				<value>com.journaldev.model.Person</value>
    			</list>
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    				<prop key="hibernate.current_session_context_class">thread</prop>
    				<prop key="hibernate.show_sql">false</prop>
    			</props>
    		</property>
    	</bean>
    
    	
    	<bean id="personDAO" class="com.journaldev.dao.PersonDAOImpl">
    		<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    	</bean>
    </beans>
    

    For hibernate 4, we need to use org.springframework.orm.hibernate4.LocalSessionFactoryBean for SessionFactory bean, Spring ORM has merged both the classes for Hibernate 3 and there is a single class now, this is good to avoid confusion. All the other configurations are same as before.

That’s it, our project is successfully migrated to Hibernate 4, neat isn’t it. Just change the SpringHibernateMain class to use spring4.xml for beans configuration and it will work fine, you will get same output as before.

You can download the final project from below link and play around with more configurations to learn more.

Comments

  1. giri says:

    Could any one please tell me how to run this project?

  2. Gayatri says:

    Hi,

    I am getting following error please help me:

    Exception in thread “main” org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name ‘hibernate3AnnotatedSessionFactory’ defined in class path resource [Spring.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1380)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:666)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:633)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1012)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:85)
    at com.SpringMvcHibernate.EmployeeMain.main(EmployeeMain.java:13)
    Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:274)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:437)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1428)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1372)
    … 10 more

  3. shivani says:

    why web.xml is not required in this example?

    1. Naseem says:

      Because its not dealing with views.

    2. Subhabrata Pandit says:

      This is a standalone project, you can see a mail method dealing with spring configuration.

  4. Jam says:

    Hi, I’m new to Spring. In the Main function there’s this line:

    PersonDAO personDAO = context.getBean(PersonDAO.class);

    Is this the same as:

    PersonDAO personDAO = context.getBean(“personDAO”);

    ?

    Thanks in advance for your reply.

    1. Nagendra says:

      Yes, It is same. You are passing ‘personDAO’ which is bean id. You should typecast it to persondao class like below. [why beacuse getBean(String beanname) returns Object.]

      PersonDAO personDAO = (PersonDAO) context.getBean(“personDAO”);

  5. Ilya says:

    Just “PERSON”! Not “Person” table name.
    When I changed it, all stay to work) thx for guide

  6. Samet says:

    Hello,
    i have one question,
    first of all i want to apoligize to you for my bad english.
    doesn’t occur SessionFactory for each dao object when we wire it with xml bean approach?
    does it need to create once if thats right?
    I hope i could express myself.

    1. Kamalakar says:

      Spring beans default scope is singleton, so only one instance of SessionFactory is created and shared.

  7. vishal says:

    Getting java.lang.IllegalArgumentException at personDAO.save(person) line in springhibernatemail class

  8. sumit says:

    Nice tutorial! thanks…………

  9. Akouri ammar says:

    Thank you so much

  10. maryetta heimann says:

    Excellent post . Speaking of which , if anyone requires a Jamaica defence force application form , my kids filled a fillable version here https://goo.gl/TNmQbl

  11. viruskimera says:

    Do you have an FTP inbound/outbound adapters example? with Maven. Please reply.

  12. Rosa says:

    Hello PANKAJ,

    Thanks for this tutorial.
    I’m trying to create CRUD application with both Spring and Hibernate: Only I found a problem with Update.
    *******************In PersonDAOImpl.java, I made:
    public void updatePerson(int id) {
    Session session = this.sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    Person p = (Person) session.load(Person.class, new Integer(id));
    session.update(p);
    tx.commit();
    session.close();
    }
    *******************In SpringHibernateMain, I made:
    Person person = personDAO.getPersonById(1);
    person3.setName(“Lisa”);
    person3.setCountry(“UK”);
    personDAO.updatePerson(person.getId());

    ———> I don’t have any error on Console but there’s any update on database.
    Can You lease tell me what’s the error or what I missed.

    Regards.

    1. Rosa says:

      Hello PANKAJ,

      It was solved.
      The problem was the use of Logger on PersonDAOImpl.

      Thanks.

  13. ALPER KOPUZ says:

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

    What I need to do for the warning ? As far as I see , I could not see an exact solution for that. I will be appreciated if you can help me.

  14. Stryder Jermaine says:

    Hi please I’m getting this error when I try to build the project in NetBeans.

    Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-jar-plugin:jar:2.3.2: Could not transfer artifact org.apache.maven.plugins:maven-jar-plugin:pom:2.3.2 from/to central (http://repo.maven.apache.org/maven2): This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server -> [Help 1]

    Please help

    1. Pankaj says:

      check your internet connections, it seems required jars are not getting downloaded. Are you behind some firewall?

  15. Imran says:

    Thanks a lot,
    Great job !!!

  16. Chen says:

    Hi,
    Can anybody tell me what’s the function of the toString() method in Person.java ?
    I’m so confused.

    1. Nishant says:

      toString() method of Person class is used wjen i simply write system.out.println(person). Same goes with any class you define. you just need to provide this method and whenever you sysout something it will automatically call this function.

    2. Mokshh says:

      Hi Chen,

      Just to represent Person class object into String representation. As if you don’t override toString() method then while printing the person object reference, it will call Object class toString() method which will return getClass().getName() + “@” + Integer.toHexString(hashCode()) representation.

      If your are using Eclipse then I would recommended to use shortcut to generate toString() method with class attributes by entering “alt+shift+s+s”

      1. Nagendra says:

        Awesome Explanation

  17. Nilvandro Muianga says:

    Hi Pankaj, this tutorial was so helpful for me. I’m so thankful.

  18. Divy Kumar says:

    I am getting following warning and after that I am not able to access the webpage.May you please help.WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/] in DispatcherServlet with name ‘appServlet’

  19. Gunns says:

    SEVERE: Servlet.service() for servlet [rest] in context with path [/WebRestDemo] threw exception [Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/Session;] with root cause
    java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/Session;

  20. Enrico says:

    Thanks a lot.
    Simple tutorial but containing all the required steps to have the example working.
    Just one hint, instead of creating the table manually with the SQL command I’d rather go with
    update
    in the spring configuration file.

  21. Alex says:

    Hi Pankaj thank you for this intro.

    I am getting this error when trying to run the JAR file

    Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/context/support/ClassPathXmlApplicationContext
    at com.journaldev.main.springHibernateMain.main(springHibernateMain.java:13)
    Caused by: java.lang.ClassNotFoundException: org.springframework.context.support.ClassPathXmlApplicationContext
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)

    The line with the error is
    ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext(“spring4.xml”);

    Any ideas?

    1. Shiva says:

      Its
      ApplicationContext context = new ClassPathXmlApplicationContext(“spring4.xml”);

  22. janis says:

    Not good example many mistakes

    1. PAblo says:

      Janis, could you please clarify ?

      1. Someone else. says:

        I’m not Janis, but I’ll give my 2 cents. After I downloaded the sourcecode and imported it to my IDE, I’m getting few errors. IDE (STS) says e.g:
        “The method list() of type PersonDAOImpl must override a superclass method”
        and
        “The method save(Person) of type PersonDAOImpl must override a superclass method”

        Also, see ClassPathXmlApplicationContext discussion in these comments.

        I’m not saying this article is bad. I’m saying Java environment setup for programming is often so complicated that if one does not manage the whole setup process, there will be problems. If one wants to find out what problems there are with this tutorial, then take a blank computer in front of you and follow this tutorial (don’t do any setup which is reguired, but missing from this tutorial, or use your knowledge which people are trying to learn using this tutorial.). You will soon find problems, because this tutorial was written for certain setup, which is impossible to duplicate with these instructions.

        Also, I could not get the tutorial sourcecode to work. After deducting I have to rename spring4.xml to spring.xml to use hibernate 4, I’m still stuck, mysql connection doesn’t work. Next, I’ll go to some other site to find a next tutorial to try. After I find one which I can get to work with decent work, I’ll really investigate how it works and start learning from it. I don’t use tutorials which I have to fix for them to be usable. Usually if I can fix them easily, I don’t need them.

  23. Surya says:

    Hi All,

    I am getting this below error after trying to do theexample in eclipse
    11:08:01,052 [ INFO] ClassPathXmlApplicationContext:510 – Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1e1c66a: startup date [Sun Sep 20 11:08:01 EDT 2015]; root of context hierarchy
    11:08:01,146 [ INFO] XmlBeanDefinitionReader:317 – Loading XML bean definitions from class path resource [spring.xml]
    11:08:01,474 [ WARN] ClassPathXmlApplicationContext:487 – Exception encountered during context initialization – cancelling refresh attempt
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate3AnnotatedSessionFactory’ defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:743)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
    at rugal.sample.core.service.impl.SpringHibernateMain.main(SpringHibernateMain.java:15)
    Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.privateGetPublicMethods(Unknown Source)
    at java.lang.Class.privateGetPublicMethods(Unknown Source)
    at java.lang.Class.getMethods(Unknown Source)
    at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
    at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
    at org.springframework.beans.CachedIntrospectionResults.(CachedIntrospectionResults.java:270)
    at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:189)
    at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:327)
    at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:359)
    at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1471)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    … 11 more
    Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 26 more
    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernate3AnnotatedSessionFactory’ defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:743)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
    at rugal.sample.core.service.impl.SpringHibernateMain.main(SpringHibernateMain.java:15)
    Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.privateGetPublicMethods(Unknown Source)
    at java.lang.Class.privateGetPublicMethods(Unknown Source)
    at java.lang.Class.getMethods(Unknown Source)
    at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
    at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
    at org.springframework.beans.CachedIntrospectionResults.(CachedIntrospectionResults.java:270)
    at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:189)
    at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:327)
    at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:359)
    at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1471)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    … 11 more
    Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 26 more

    Regards
    Surya

    1. pape says:

      you have to vrified the location of the spring config file and refenced it in your web.xml

  24. Deepak says:

    Hi Pankaj Sir ,

    Really nice example . But you have not defined HibernateTransactionManager in this , So my question is that if the TransactionManagers of spring are required in the case where we are using declarative transaction management of spring and the application is deployed in any j2ee container ?

  25. Deepak says:

    Hi Pankaj Sir , Really good example this is .

    There are different transaction managers in spring. And you have not used hibernate transaction manager in this example . So my question is for the j2ee container application only where we are doing declarative transaction management the transaction managers are required ? Suppose I do not want to use any of them and my application is not residing inside any j2ee container .Then in this case if we really need to define the transaction managers ?

  26. Subramanya says:

    Also add to servlet-context.xml if you are facing the error as WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/] in DispatcherServlet with name ‘appServlet’

  27. Hicham says:

    Can you help me please,

    I use spring with hibernate3, when i test my program with JUnit, i have this message :
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.context.annotation.internalRequiredAnnotationProcessor’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.transaction.config.internalTransactionAdvisor’: Cannot create inner bean ‘(inner bean)’ of type [org.springframework.transaction.interceptor.TransactionInterceptor] while setting bean property ‘transactionInterceptor’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘(inner bean)’: Cannot resolve reference to bean ‘transactionManager’ while setting bean property ‘transactionManager’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘transactionManager’ defined in class path resource [application-context.xml]: Cannot resolve reference to bean ‘sessionFactory’ while setting bean property ‘sessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [application-context.xml]: Cannot resolve reference to bean ‘dataSource’ while setting bean property ‘dataSource’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘dataSource’ is defined
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:485)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:883)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:593)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:351)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:122)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:66)
    at com.university.service.CourseServiceTest.setUpBeforeClass(CourseServiceTest.java:17)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    application-context.xml :

    com.university.model.Course
    com.university.model.Student
    com.university.model.Teacher

    org.hibernate.dialect.MySQLInnoDBDialect

  28. Muhammad Asif says:

    Excellent job, really interested and informative.

  29. Umesh Annegirikar says:

    @Column(name=”id”)
    @GeneratedValue(strategy=GenerationType.IDENTITY) not working for me i have used @Column (name=”id”,nullable=false) @GeneratedValue(strategy=GenerationType.AUTO) then it working fine cod e is explaining excellent

  30. El. says:

    Very good tutorial. Thank you so much for that work. have a nice Day. EL..

  31. Derick Daniek says:

    Hey pankaj, in spring4.xml you have used annotation mapping, and in class name you have given “localSessionFactoryBean”, if i am not wrong “localSessionFactoryBean” is used for XML mapping, if so then why have you used it with “hibernate4AnnotatedSessionFactory”.
    Correct me if i am wrong, as i am new to Spring+Hibernate integration

  32. Krishna Srinivasan says:

    Good article!

  33. Vinod says:

    Hi Pankaj,

    could you please confirm which maven archetype you have used to develop above mentioned application.

  34. Surendra says:

    Very well written example. Thoroughly understood. I know Hibernate and Spring Injection. Never worked on this integration. Now I’m able to do it on my own. Much appreciated work.

  35. Dave says:

    This is a well put together tutorial – thanks

  36. Dheeraj Kumar says:

    I’m integrating spring3.1 with hibernate4.0 i I’m getting blew error

    ava.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2291)
    at java.lang.Class.getDeclaredFields(Class.java:1743)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:372)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:320)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:830)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:493)

    HIbernate Configuration xml

    org.hibernate.dialect.Oracle10gDialect
    true
    10
    true
    true
    thread
    true

    com.dcs.employee.model.Employee

    1. Chandra Bhanu Rastogi says:

      It seems compatibility issue. You are using hibernate 4.x but somewhere at runtime it’s trying to use spring classes which are hibernate 3 compatible. Check all the beans defined in configration xml and make sure you don’t pass hibernate 3 compatible classes of spring.

    2. Prem Tiwari says:

      Hi Dheeraj,

      Please replace bleow in your pom.xml and you are done :).

      4.3.5.Final

  37. papepula says:

    Hi, when i start my app with string boot run then it works.
    But i get this excpetion when i wanna deploy the war file on a tomcat 7.
    I did exactly the same but my tomcat doesnt know the hibernate.dialect.
    I also tried to remove the hibernate.dialect because it isn’t necessary to declared it
    and the app should select automatically one. I tried so much but nothing works…
    Hope someone has an idea.

    org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/myapp-0.0.1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:553)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1648)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1445)
    at org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServlet.java:284)
    at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:206)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:213)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:975)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:752)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
    at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
    at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5456)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 40 more
    Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
    … 58 more

  38. Bhawani Shanker says:

    I need Spring 4 MVC 1-on-1 training starting right from setting up web apps development environment (JDK8, Spring 4, Gradle etc) supports.

    Who can help?

  39. Alex says:

    this was very helpful to understand the spring hibernate integration

  40. Vijay Ambekar says:

    Great work!!! Thanks. It worked for me. 🙂

  41. Ruby says:

    Thank so much. It is very helpful for beginer like me.

  42. Aarti says:

    All of your tutorial are really helpful… Good Work & Thank You!!!!

  43. Biplab says:

    Hi Pankaj,
    Great tutorial for spring beginners. I just wanted to know if we could use oracle.jdbc.pool.OracleDataSource as a data source instead of org.apache.commons.dbcp.BasicDataSource. I am using oracle 10g xe.
    Thanks !!

    1. Pankaj says:

      Yes we can use any of the DataSource implementation.

      1. Biplab says:

        Thanks for the reply. I will try that one.

  44. Deevaker Bhatia says:

    sir i want to create an application employee management i want to use STS Hibernate maven …..can you help me out in this webapp

  45. aditya says:

    in create table u say `Person` but in entity the table name is ‘PERSON’ its different and making error

    1. Pankaj says:

      Usually database table name is not case sensitive. Looks like not the case with your database.

      1. lib says:

        Just wanted to add that I also got a SQLException saying testdb.PERSON doesn’t exist when my table name was Person. I’m using mysql 5.5.40

        1. Pankaj says:

          I got the root cause of the issue. I am using Mac OS X as my development machine and I believe you guys are using some other form of Unix. According to MySQL Reference manual for case sensitivity:

          Consequently, the case sensitivity of the underlying operating system plays a part in the case sensitivity of database and table names. This means database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix. One notable exception is Mac OS X, which is Unix-based but uses a default file system type (HFS+) that is not case sensitive.

          Reference: http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html

          NOTE: To avoid this issue for other users, I have updated the post accordingly.

  46. Ivan says:

    Hello, I have couple question regarding to your post.
    1. Why don’t you use Spring @Autowired in your DAO and why don’t use this instead?

    public void save(Person person)
    {
    this.sessionFactory.getCurrentSession().save(person);
    }

    Because I don’t know whether you use Transaction for any benefits?

    2. Could you give more example if you create another class to wrap PersonDAOImpl to it gonna be like:

    @Service
    @Transactional(readOnly = true)
    public class PersonServiceImpl implements PersonService
    {
    @Autowired
    protected PersonDao personDao;

    public List getPersons()
    {
    return this.personDao.getAll();
    }

    @Transactional(readOnly = false)
    public void save(Person person)
    {
    this.personDao.save(person);
    }
    }

    Because #2 don’t work for me, it said that I’ve configured more than 1 autowired? I’m new to hibernate 4 and Spring 4, so I need some answers for this updates. And also please bring it with your spring-config.xml in case mapping for this service class I assume would be better for hierarchical software achitecture.

    Thank you for your assistance.

  47. Muhammed AbdElFatah says:

    I am newbie in hibernate with spring and i am really thank you for this tutorial .

    I tested hibernate v3 with spring v4 and it works good , but when i changed it with hibernate v4
    it gives to me this error >>>

    Exception in thread “main” java.lang.UnsupportedOperationException: The user must supply a JDBC connection
    at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
    at db.dao.EmployeeDAOImpl.saveEmployee(EmployeeDAOImpl.java:22)
    at db.main.SpringHibernateMain.main(SpringHibernateMain.java:23)

    i searched a lot about this error and cannot find any solution.

    thank you ^_^

  48. Andrei Anpilogov says:

    Big thanks!

    1. right_now says:

      Nice tutorial! There’s a great RAD tool out called Jigy Generator that automatically spits you out a fully configured spring project which can already connect to your database, authenticate users, handle file uploads, etc. It even creates dao’s, domain objects and validators in your project by reverse engineering your database. You can download the project at http://www.getjigy.com

  49. Sunil says:

    Thank you so much . Its very helpful tutorials

  50. Rizwan Mursaleen says:

    It was very helpful and very clear. Thank you.

  51. Suresh says:

    Hi pankaj, do you have any spring and hibernate real time project. If it’s there I will pay you

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