It is very simple to integrate Spring with Hibernate. In Hibernate framework, we provide all the database information hibernate.cfg.xml file. But if we are going to integrate the hibernate application with spring, we don’t need to create the hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.
Why Spring with Hibernate?
Spring framework provides HibernateTemplate class, so you don’t need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc. So it saves a lot of code.
Understanding problem without using Spring:
Let’s understand it by the code of hibernate given below:
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//creating session factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Employee e = new Employee(100,"amar",40000);
session.persist(e);//persisting the object
t.commit();//transaction is committed
session.close();
As you can see in the code with only using Hibernate, you have to follow so many steps.
Solution by using HibernateTemplate class of Spring Framework:
Employee e=new Employee(100,"amar",40000);
hibernateTemplate.save(e1);
Steps for Spring and Hibernate integration
- create table in the database It is optional.
- create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
- create Employee.java file It is the persistent class
- create employee.hbm.xml file It is the mapping file.
- create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
- create InsertTest.java file It calls methods of EmployeeDao class.
An example of directory structure for Spring and Hibernate integration is shown below.

You can enable hibernate properties like automatic table creation by hbm2ddl.auto and show sql queries in applicationContext.xml file as below.
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
