Persisting Object with Spring 3.1 and Hibernate 4

Spring framework allows to easily configure an Hibernate datasource.
When using an ORM framework on its own, you have to configure its resource factory with its API. For Hibernate and JPA, you have to build a session factory and an entity manager factory from the native Hibernate API and JPA.
You have no choice but to manage these objects manually, without Spring’s support.

Spring provides several factory beans for you to create a Hibernate session factory or a JPA entity manager factory as a singleton bean in the IoC container. These factories can be shared between multiple beans via dependency injection. Moreover, this allows the session factory and the entity manager factory to integrate with other Spring data access facilities, such as data sources and transaction managers.

In this tutorial we will see how to persist object using Hibernate 4 in a Spring 3.1 based web-application. This simple web app manages a single entity Person with the following DDL:

  firstname varchar(255) DEFAULT NULL,
  lastname varchar(255) DEFAULT NULL,


  • Spring 3.1.1
  • Hibernate 4.1.3
  • MySQL 5.5
  • Apache DBCP Commons Library

1 The POM file

<project xmlns="" xmlns:xsi=""


		<!-- Spring framework -->
		<dependency> <!-- Used for Hibernate4 LocalSessionFactoryBean -->

		<!-- AOP dependency -->

		<!-- Persistence Management -->
		<dependency> <!-- Apache BasicDataSource -->

		<dependency> <!-- MySQL database driver -->

		<dependency> <!-- Hibernate -->

2 Entity class

With hibernate an entity class it’s a POJO class with JPA2 annotation. The class that represents our entity “person” is the following:

package org.madbit.hibernate.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

public class Person {
	private int pid;
	private String firstname;
	private String lastname;

	public int getPid() {
		return pid;

	public void setPid(int pid) { = pid;

	public String getFirstname() {
		return firstname;

	public void setFirstname(String firstname) {
		this.firstname = firstname;

	public String getLastname() {
		return lastname;

	public void setLastname(String lastname) {
		this.lastname = lastname;

3 The DAO

Now we can implement a simple DAO that allow to add new person in the database. Below the java code of

package org.madbit.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.madbit.hibernate.entity.Person;
import org.springframework.transaction.annotation.Transactional;

public class MyDAO {
	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	public void addPerson(Person p) {
		Session session = sessionFactory.openSession();;

4. Configuring Data access

4.1 Hibernate

Let’s create a bean configuration file for using Hibernate as the ORM framework datasource.xml in the classpath root (src/main/resources).

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/mytest" />
	<property name="username" value="root" />
	<property name="password" value="" />
	<property name="initialSize" value="2" />
	<property name="maxActive" value="5" />

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<property name="packagesToScan" value="org.madbit.hibernate.entity" />
	<property name="hibernateProperties">
			<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
			<prop key="">update</prop>
			<prop key="hibernate.show_sql">false</prop>

<bean id="myDAO" class="org.madbit.hibernate.dao.MyDAO" >
	<property name="sessionFactory" ref="sessionFactory" />

4.2 Transaction Managment

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory" />

<tx:annotation-driven transaction-manager="transactionManager"/>

enable transaction managment on method annotated with @Transactional. Basically in that file are configured three beans, that is:

  • Datasource
  • Session-factory
  • DAO
  • Transaction Managment

4.2 Datasource

There are several data source implementations. Spring’s own data source implementations are mainly used for testing purposes. Database Connection Pooling Services (DBCP) module of the Apache Commons Library has several data source implementations that support connection pooling. We use BasicDataSource allows you to specify the initial connection size and maximum active connections for the connection pool.

4.3 Session Factory

When working with Hibernate, there are 2 common ways of writing your mapping: XML and annotations. Spring-Hibernate 3 integration allows you to configure 2 kinds of SessionFactoryBean:

  • LocalSessionFactoryBean for xml mapping only
  • AnnotationSessionFactoryBean for xml mapping and/or Annotation-based mapping

With Spring 3.1 and Hibernate 4, things are now simpler: there is only one SessionFactoryBean called LocalSessionFactoryBean (class org.springframework.orm.hibernate4.LocalSessionFactoryBean). It works with both annotation-based mapping and xml-based mapping. Subclass of Spring’s standard LocalSessionFactoryBean for Hibernate, supporting JDK 1.5+ annotation metadata for mappings. With property packagesToScan it’s possible tell to Hibernate which package contains the JPA2 annotated classes representing the Database Entities. In alternative it’s possible specify the set of classes to be bound as a list, like this:

<property name="classesToBeBound">

This can be useful if you have JPA2 annotated classes in different package.

4.4 DAO configuration

The last bean declare the DAO passing the sessionFactory using setter injection.

5 AddPerson servlet

In order to insert new data we can implement a simple HTML page with a form containing all the Person’s attributes.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add user</title>
	<form action="addPerson" method="post">
		First name: <input type="text" name="firstname">
		Last name: <input type="text" name="lastname">
		<input type="submit" value="Save">

The form action call the servlet addPerson. Below the servlet’s implementation:

package org.madbit.hibernate.web;

import org.madbit.hibernate.dao.MyDAO;
import org.madbit.hibernate.entity.Person;
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.bind.annotation.RequestParam;

public class PersonController {
	@RequestMapping(value="/addPerson", method=RequestMethod.POST) 
	public String addPerson(@RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname, Model model) {
		Person p = new Person();
		return "/result.jsp";

As you can see, the servlet retrieve the form data from the HTTP request, create a new Person and insert it in the database throught the DAO. Using @Autowired annotation you can get an already instantiated MyDAO Object from Spring IoC container. You have to enable register @Autowired annotation, as following:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

To configure the “person” (as declared in web.xml file) controller in Spring, you have to define a person-servlet.xml configuration file under /WEB-INF, as showed below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

	<!-- Used for scan Controller Spring annotations -->
	<context:component-scan base-package="org.madbit.hibernate.web" />

5 Web deployment descriptor

The final web.xml with the addPerson servlet declaration file is the following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="" xmlns:xsi=""

	<display-name>Spring Hibernate</display-name>


ApplicationContext file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

	<import resource="classpath:datasource.xml"/>
	<!-- Register @Autowired annotation -->
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

If you want to learn more retro games news, read our magazine and subscribe to our newsletter.