Spring Hibernate Integration Tutorial

DZone 's Guide to

Spring Hibernate Integration Tutorial

Check out this tutorial about integrating Spring and Hibernate.

· Database Zone ·
Free Resource

originally published on 6/15/12

in this tutorial, you will see how to integrate spring and hibernate. i assume you are comfortable with both. at the end of this example, you will learn to create a form through which you can add a user and list all the existing users, as shown below.

here is the directory structure of the example.

you need to have the following lib files in the web-inf/lib directory.


the most important part of the example is the spring bean configuration. here is the spring bean configuration file.

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="viewresolver" class="org.springframework.web.servlet.view.
    internalresourceviewresolver" p:prefix="/web-inf/jsp/" p:suffix=".jsp" />

<bean id="mydatasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close">
<property name="driverclassname" value="org.hsqldb.jdbcdriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value=""/>

<bean id="mysessionfactory" class="org.springframework.orm.hibernate3.
<property name="datasource" ref="mydatasource" />
<property name="annotatedclasses">
<property name="hibernateproperties">
<prop key="hibernate.dialect"> org.hibernate.dialect.hsqldialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>

<bean id="myuserdao" class="com.vaannila.dao.userdaoimpl">
<property name="sessionfactory" ref="mysessionfactory"/>

<bean name="/user/*.htm" class="com.vaannila.web.usercontroller" >
<property name="userdao" ref="myuserdao" />


here, we use the jakarta commons dbcp basicdatasource to set up a jdbc datasource . i am using hsqldb database here. if you are using mysql, then you need to change this configuration.

hibernate sessionfactory can be configured in the spring bean configuration file itself, as shown above. you need not have a separate hibernate configuration file (hibernate.cfg.xml ) to do this. i am using hibernate annotations in this example, so i am listing all the annotated classes using the annotatedclasses property. all the hibernate-related configurations can be done using the hibernateproperties .

we use a separate dao class to interact with the database. using a setter injection, we inject the hibernate sessionfactory.

we have a multiactioncontroller class to handle the web requests, so we use a wildcard character in the bean name (" /user/*.htm ").

here is the user class with the hibernate annotations. if you want to add any database-related constraints, then you need to do it here.

package com.vaannila.domain;

import javax.persistence.column;
import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.id;
import javax.persistence.table;

public class user {

private long id;
private string name;
private string password;
private string gender;
private string country;
private string aboutyou;
private string[] community;
private boolean mailinglist;

public long getid() {
return id;
public void setid(long id) {
this.id = id;

public string getname() {
return name;
public void setname(string name) {
this.name = name;

public string getpassword() {
return password;
public void setpassword(string password) {
this.password = password;

public string getgender() {
return gender;
public void setgender(string gender) {
this.gender = gender;

public string getcountry() {
return country;
public void setcountry(string country) {
this.country = country;

public string getaboutyou() {
return aboutyou;
public void setaboutyou(string aboutyou) {
this.aboutyou = aboutyou;

public string[] getcommunity() {
return cohttp://www.dzone.com/node/add/articlemmunity;
public void setcommunity(string[] community) {
this.community = community;

public boolean getmailinglist() {
return mailinglist;
public void setmailinglist(boolean mailinglist) {
this.mailinglist = mailinglist;


our dao class implements the userdao interface, and here, we have just two methods: one to save the user details and the other to list all the users.

package com.vaannila.dao;

import java.util.list;
import com.vaannila.domain.user;

public interface userdao {

public void saveuser(user user) ;
public list<user> listuser() ;

in the dao class, we use hibernate template to access the database. to create a hibernate template instance, you need a session factory. for this purpose, we injected the sessionfactory property in the spring bean configuration file.

package com.vaannila.dao;

import java.util.list;
import org.hibernate.sessionfactory;
import org.springframework.orm.hibernate3.hibernatetemplate;
import com.vaannila.domain.user;

public class userdaoimpl implements userdao {

private hibernatetemplate hibernatetemplate;

public void setsessionfactory(sessionfactory sessionfactory) 
this.hibernatetemplate = new hibernatetemplate(sessionfactory);

public void saveuser(user user) {

hibernate template is thread-safe and reusable. you need not manually open and close session; hibernate template will do that for you.

the usercontroller class extends multiactioncontroller class. the userdaoimpl instance is injected using a setter injection. in the add method, we call the saveuser() method and redirect the control to the " list.htm " url. this will invoke the list() method. in the list method, you add two things to the modelmap: the user list to display the list of users and an instance of the user object to bind the form fields in the userform.jsp page.

package com.vaannila.web;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.springframework.ui.modelmap;
import org.springframework.web.servlet.modelandview;
import org.springframework.web.servlet.mvc.multiaction. multiactioncontroller;

import com.vaannila.dao.userdao;
import com.vaannila.domain.user;

public class usercontroller extends multiactioncontroller {

private userdao userdao;

public void setuserdao(userdao userdao) {
this.userdao = userdao;

public modelandview add(httpservletrequest request,
httpservletresponse response, user user) throws exception {
return new modelandview("redirect:list.htm");

public modelandview list(httpservletrequest request,
httpservletresponse response) throws exception {
modelmap modelmap = new modelmap();
modelmap.addattribute("userlist", userdao.listuser());
modelmap.addattribute("user", new user());
return new modelandview("userform", modelmap);

in the jsp page, we use spring form tags to display the form fields and jstl tags to display the list of users.

<%@ page language="java" contenttype="text/html; charset=iso-8859-1"
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
.even {
background-color: silver;
<title>registration page</title>

<form:form action="add.htm" commandname="user">
<td>user name :</td>
<td><form:input path="name" /></td>
<td>password :</td>
<td><form:password path="password" /></td>
<td>gender :</td>
<td><form:radiobutton path="gender" value="m" label="m" /> 
            <form:radiobutton path="gender" value="f" label="f" /></td>
<td>country :</td>
<td><form:select path="country">
<form:option value="0" label="select" />
<form:option value="india" label="india" />
<form:option value="usa" label="usa" />
<form:option value="uk" label="uk" />
<td>about you :</td>
<td><form:textarea path="aboutyou" /></td>
<td>community :</td>
<td><form:checkbox path="community" value="spring" label="spring" />
                <form:checkbox path="community" value="hibernate" label="hibernate" />
                <form:checkbox path="community" value="struts" label="struts" /></td>
<td><form:checkbox path="mailinglist"
label="would you like to join our mailinglist?" /></td>
<td colspan="2"><input type="submit" value="register"></td>
<c:if test="${fn:length(userlist) > 0}">
<table cellpadding="5">
<tr class="even">
<th>about you</th>
<c:foreach items="${userlist}" var="user" varstatus="status">
<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">

now you can execute the example by running the redirect.jsp page. you will see the following page.

after entering a few records, you will see the user's list displayed below.

you can download and try the example here.

database, integrate spring and hibernate, spring, sql, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}