Spring Hibernate Integration

Respected Readers,

This post will run through a working example of integrating Spring and Hibernate frameworks. There are multiple ways to doing it, this blog mentions them.  I am going to use the SessionFactory approach.

Imagine a web application that has a login page. The user enters user id and password. The user is authenticated by checking for these values in USER table in MySQL database. So let’s put the pieces together.

1) Basically a JDBC datasource should be created and then a Hibernate SessionFactory on top of it. Below springhibernateexample-db-properties.xml declares this configuration.

<?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:p="http://www.springframework.org/schema/p"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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.xsd">

<bean id="blogDataSource" class="org.apache.commons.dbcp.BasicDataSource"
 <property name="driverClassName" value="com.mysql.jdbc.Driver" />
 <property name="url" value="jdbc:mysql://localhost:3306/blog_schema" />
 <property name="username" value="blog" />
 <property name="password" value="blog" />

<bean id="blogSessionFactory"
 <property name="dataSource" ref="blogDataSource" />
 <property name="hibernateProperties"
 value="hibernate.dialect=org.hibernate.dialect.MySQLDialect" />


2) A basic login.jsp page that accepts user id and password.

<form name="input" action="login.htm" method="post">
User Id: <input type ="text" name="userid" /> <br />
Password: <input type ="text" name="password" /> <br />
<input type="submit" value="Login" />

3) Associated LoginController.java. It contains reference to LoginUtil.java that does the work of talking to the database.

package com.springhibernate.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.springhibernate.util.LoginUtil;
public class LoginController extends AbstractController {

protected ModelAndView handleRequestInternal(HttpServletRequest request,
 HttpServletResponse response) throws Exception {

 String userId = ServletRequestUtils.getStringParameter(request, "userid", null);
 String password = ServletRequestUtils.getStringParameter(request, "password", null);

 return getLoginUtil().isUserExists(userId, password) == true ? new ModelAndView("welcome") : new ModelAndView("login");


private LoginUtil loginUtil;

public LoginUtil getLoginUtil() {
 return loginUtil;

public void setLoginUtil(LoginUtil loginUtil) {
 this.loginUtil = loginUtil;


4) LoginUtil.java. This class has reference to the Hibernate SessionFactory created. Using SessionFactory, Hibernate Session is obtained. Session class has various methods to interact with database.

package com.springhibernate.util;

import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class LoginUtil {

public boolean isUserExists(String userId, String password) {
 Session session = getSessionFactory().openSession();
 try {
 String sqlText = "select count(1) rowcount from user u where user_id=? and password =?";
 SQLQuery sqlQuery = session.createSQLQuery(sqlText).addScalar(
 "rowcount", Hibernate.INTEGER);
 sqlQuery.setString(0, userId);
 sqlQuery.setString(1, password);
 int rowCount = (Integer) sqlQuery.uniqueResult();
 System.out.println("user id: " + userId + ", password: " + password
 + ", rowCount: " + rowCount);
 return rowCount == 1 ? true : false;
 } finally {


private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
 return sessionFactory;

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


5. Next we define springhibernateexample-servlet.xml that declares all the beans and configures URL mappings and view resolver.

<?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:p="http://www.springframework.org/schema/p"
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="loginController" class="com.springhibernate.web.LoginController">
 <property name="loginUtil" ref="loginUtil" />

<bean id="welcomeController" class="com.springhibernate.web.WelcomeController" />

<bean id="loginUtil" class="com.springhibernate.util.LoginUtil">
 <property name="sessionFactory" ref="blogSessionFactory" />

<bean id="simpleUrlMapping"
 <property name="mappings">
 <prop key="/login.htm">loginController</prop>
 <prop key="/welcome.htm">welcomeController</prop>

<bean id="viewResolver"
 <property name="prefix" value="/WEB-INF/jsp/" />
 <property name="suffix" value=".jsp" />


6. Below is the DDL for USER table in BLOG_SCHEMA that is used for authentication:

DROP TABLE IF EXISTS `blog_schema`.`user`;
CREATE TABLE `blog_schema`.`user` (
 `user_id` varchar(45) NOT NULL DEFAULT '',
 `password` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`user_id`)

7. Below is web.xml that specifies to load additional configuration file that contains Datasource and SessionFactory declartions:

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




This project can be downloaded from here.

WAR can be downloaded from here. You will obviously need to install MySQL server instance to run it on your machine.

Thanks for reading this post, looking forward to your comments.

Your’s Truly

About Badal Chowdhary

I am a Software Engineer by profession. I have done SCJP and SCWCD certifications. Like working on cutting edge technologies and frameworks. Driven by challenges and fascinated by technology. I love playing and watching sports: Cricket, Ping Pong, Tennis, Badminton, Racket Ball and Gym.
This entry was posted in Hibernate, Spring and tagged , , , , , , , , . Bookmark the permalink.

7 Responses to Spring Hibernate Integration

  1. kaif khan says:

    great example.but the validation is not provided

  2. Anonymous says:

    Hi, This is Maaz… Good working example… Can any one show me a good example for Spring Security ?

  3. neha says:

    can u please explain the project structure

  4. abhishek says:

    hI Badal,

    A very good example.

    i am facing the following issues, can you please guide.thanks in advance.

    1.When i imported this project this project into the eclipse everything was imported except the source files.

    2.Project zip does not seem to be available


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s