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:context="http://www.springframework.org/schema/context"
 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"
 destroy-method="close">
 <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>

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

</beans>

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" />
</form>

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 {
 session.close();
 }

}

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"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="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/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>

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

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

<bean id="simpleUrlMapping"
 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 <property name="mappings">
 <props>
 <prop key="/login.htm">loginController</prop>
 <prop key="/welcome.htm">welcomeController</prop>
 </props>
 </property>
 </bean>

<bean id="viewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/jsp/" />
 <property name="suffix" value=".jsp" />
 </bean>

</beans>

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`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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">
 <display-name>springhibernateexample</display-name>
 <servlet>
 <servlet-name>springhibernateexample</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/conf/springhibernateexample-servlet.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

<servlet-mapping>
 <servlet-name>springhibernateexample</servlet-name>
 <url-pattern>*.htm</url-pattern>
 </servlet-mapping>

<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 /WEB-INF/conf/springhibernateexample-db-properties.xml
 </param-value>
 </context-param>
</web-app>

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

    Thanks.

Leave a comment