Hibernate and Spring Integration
We can simply integrate hibernate application with spring application.
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.
Advantage of Spring framework with hibernate
The 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:
As you can see in the code of sole hibernate, you have to follow so many steps.
Solution by using HibernateTemplate class of Spring Framework:
Now, you don't need to follow so many steps. You can simply write this:
Let's see what are the simple steps for hibernate and spring 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.
Example of Hibernate and spring integration
In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of spring and hibernate example.
1) create the table in the database
In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database
It is a simple POJO class. Here it works as the persistent class for hibernate.
This mapping file contains all the information of the persistent class.
It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.
In this file, we are providing all the informations of the database in the BasicDataSource object.
This object is used in the LocalSessionFactoryBean class object, containing some other informations such as mappingResources and hibernateProperties.
The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code of applicationContext.xml file.
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.
Now, if you see the table in the oracle database, record is inserted successfully.
Enabling automatic table creation, showing sql queries etc.
You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's see the code:
If you write this code, you don't need to create table because table will be created automatically.