Over a million developers have joined DZone.

Spring Hibernate Integration Tutorial

DZone's Guide to

Spring Hibernate Integration Tutorial

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

In this tutorial you will see how to integrate spring and hibernate. I assume you are comfortable with both spring and hibernate. 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 setup 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 seperate 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 seperate DAO class to interact with the database. Using setter injection we inject the Hibernate SessionFactory.

We have a MultiActionController class to handle the web requests, so we use wildcard charcter 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, here we have just two methods one to save the user details and 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 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.

Aftering entering few records you will see the user's list dispalyed below.

You can download and try the example here.

Source : Download



Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}