Community Pick: Many members of our community have endorsed this article.

Spring Hibernate Integration

   When I first started to learn Hibernate I found it pretty easy, but integrating it with Spring took me around 2 weeks. Not pretty cool. So I came up with the idea of writing this article which guides you simply towards the integration.

NOTE : This article assumes that you've a basic knowledge in Spring so that I don't need to start from scratch.

Its a five step process :
1. Create a hibernate configuration file
2. Create a mapping file for each DB
3. Write the POJO class
4. Call the Session Factory to access DB using Hibernate
5. Controller to finish the course

1. Create a hibernate configuration file

It's pretty common to write a hibernate-cfg.xml file, but due to the extreme flexibility of Spring, we dont need to write them all. It is completely customised so easy to write. A Sample hibernate context file is shown below. The file itself a self explained one.

<?xml version="1.0" encoding="UTF-8"?>
                      <beans xmlns=""
                      	xmlns:xsi="" xmlns:p=""
                      	xmlns:jee="" xmlns:tx=""
                      		========================= RESOURCE DEFINITIONS
                      		Configurer that replaces ${...} placeholders with values from a
                      		properties file
                      		(in this case, JDBC-related settings for the dataSource definition
                      	<context:property-placeholder location="" />
                      		Uses Apache Commons DBCP for connection pooling. See Commons DBCP
                      		documentation for the required JAR files. Alternatively you can use
                      		another connection pool such as C3P0, similarly configured using
                      	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
                      		destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
                      		p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
                      	<!-- Hibernate SessionFactory -->
                      	<bean id="sessionFactory"
                      		p:dataSource-ref="dataSource" p:mappingResources="dbtables.hbm.xml">
                      		<property name="hibernateProperties">
                      				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
                      				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                      				<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                      		<property name="eventListeners">
                      				<entry key="merge">
                      						class="" />
                      		Transaction manager for a single Hibernate SessionFactory (alternative
                      		to JTA)
                      	<bean id="transactionManager"
                      		p:sessionFactory-ref="sessionFactory" />
                      		========================= BUSINESS OBJECT DEFINITIONS
                      		Activates various annotations to be detected in bean classes: Spring's
                      		@Required and @Autowired, as well as JSR 250's @Resource.
                      	<context:annotation-config />
                      		Instruct Spring to perform declarative transaction management
                      		automatically on annotated classes.
                      	<tx:annotation-driven />
                      		Exporter that exposes the Hibernate statistics service via JMX.
                      		Autodetects the service MBean, using its bean name as JMX object name.
                      	<context:mbean-export />
                      		Project's central data access object: Hibernate implementation
                      	<bean id="login" class="org.Spring.project.service.ILoginImpl" />

Open in new window

Simple isn't it. The code itself self-descriptive and explains each and every line of code.
Hopefully, nothing more to say.

2. Create a mapping file for each DB

Now let's start to write a mapping file. Mapping file is nothing but a XML file which maps the tables to the POJO (or) bean files, so that we can use the bean to process the DB instead of writing tedious SQL queries and large java code. I think this is what ORM's are for.
The sample hbm.xml file is (hbm -> Hibernate Mapping File)

<?xml version="1.0" encoding="UTF-8"?>
                      <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
                        - Mapping file for the Hibernate implementation of the Login Interface
                      <hibernate-mapping auto-import="true" default-lazy="false">
                      		<class name="org.spring.project.model.Registration" table="Login">
                                      <!--This code emphasize that usr_id is the primary key-->
                      		<id name="usr_id" column="usr_id">
                                      <!--Other fields in the DB-->  
                      		<property name="usr_name" column="usr_name"/>
                      		<property name="usr_password" column="usr_password"/>

Open in new window

So, what does this file do? Simply said, I have a table called Login which I want to map to POJO (or) Bean file

The name of the property refers to the bean variable, whereas the column refer to the table field.

3. Write the POJO class

Now we tell the spring that the Login table is mapped to But where is the Bean file? It's nothing but a simple POJO file with getters and setters for the table fields.

package org.spring.project.model;
                      public class Registration
                             private String usr_id;
                             private String usr_name;
                             private String usr_password;
                      	public String getUsr_id() {
                      		return usr_id;
                      	public void setUsr_id(String usrId) {
                      		usr_id = usrId;
                      	public String getUsr_name() {
                      		return usr_name;
                      	public void setUsr_name(String usrName) {
                      		usr_name = usrName;
                      	public String getUsr_password() {
                      		return usr_password;
                      	public void setUsr_password(String usrPassword) {
                      		usr_password = usrPassword;

Open in new window

4. Call the Session Factory to access DB using Hibernate

In Spring, every major processing has to be implemented in the Service Implementation.
At this point, we need to wire up our session Factory with the Service Implementation to play with the DB, that can also be achieved without writing any ugly SQL queries.

package org.spring.project.service;
                      import org.apache.log4j.Logger;
                      import org.hibernate.Criteria;
                      import org.hibernate.SessionFactory;
                      import org.hibernate.criterion.Expression;
                      import org.springframework.beans.factory.annotation.Autowired;
                      import org.springframework.stereotype.Repository;
                      import org.springframework.transaction.annotation.Transactional;
                      import org.spring.project.model.Registration;
                      public class ILoginImpl implements ILogin {
                      	private SessionFactory sessionFactory;
                      	private final Logger log = Logger.getLogger(ILoginImpl.class);
                      	public void insertData(Registration reg) {
              "Inside implementation");

Open in new window

The class is annotated with @Service(“loginservice”).  This is the meta data that Spring will use when autowiring the userService property in the Controller created in the previous step.  We’ve explicitly defined the name “loginservice” in the annotation’s value, otherwise without it Spring would have named the bean “loginservice” automatically and the autowiring of this bean in the Controller and other classes would have failed.

@Transactional annotation will be recognized by the tx:annotation-driven element in the application context.  Having placed the annotation at the class level means that all methods in this class by default should adhere to these transaction rules.  

A Session Factory object gets autowired.  That class will deal with the actual ORM framework, in this case, Hibernate.

5. Controller to finish the course

Each and every request from JSP page will go to Controller and responses dispatched from Controller. Let's see a simple controller which gets the input and pass them to service, and return back the result to JSP Page.

package org.spring.project.web;
                      import org.springframework.beans.factory.annotation.Autowired;
                      import org.springframework.stereotype.Controller;
                      import org.springframework.ui.Model;
                      import org.springframework.web.bind.annotation.RequestMapping;
                      import org.springframework.web.bind.annotation.RequestMethod;
                      import org.springframework.web.servlet.ModelAndView;
                      import org.tbingo.project.model.PGRequestModel;
                      import org.spring.project.service.ILogin;
                      public class LoginController{	
                      	private final ILogin login;
                      	public PGForwardController(ILogin login) {
                      		this.login = login;
                      	public String forwardPG(Registration reg,Model model){
                                      String message = "";
                                      {success="Data inserted successfully";}
                                      else{success="Problem inserting Data";}
                                      model.addAttribute("message",success);//Pass the msg to a JSP page
                      		return "reg_success";//name of the JSP page
                                      // To display the msg in JSP page, use ${message}. Thats it		

Open in new window

Now you're set to go. Start the server, point your browser towards the login page and see how the data get inserted without writing even a single SQL query. Hibernate will do that for you.
If you want to see the query generated by SQL set the "show-sql' attribute as true in hibernate-configuration file.

If you have any queries, please feel free to contact me.

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.