Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse


: 9

[ad name=”AD_INBETWEEN_POST”] Let us make a complete end-to-end application using Spring 3.0 MVC as front end technology and Hibernate as backend ORM technology. For this application we will also use Maven for build and dependency management and MySQL as database to persist the data.

The application will be a simple Contact Manager app which will allow user to add new contacts. The list of contacts will be displayed and user will be able to delete existing contacts.

Our Goal

As describe above, our goal is to create a contact manager application which will allow the user to add a contact or remove it. The basic requirement of the Contact Manager app will be:

  1. Add new contact in the contact list.
  2. Display all contacts from contact list.
  3. Delete a contact from contact list.

Spring 3.0 MVC Series


Following is the screenshot of end application.

Application Architecture

We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called ContactService.

Getting Started

For our Contact Manager example, we will use MySQL database. Create a table contacts in any MySQL database. This is very preliminary example and thus we have minimum columns to represent a contact. Feel free to extend this example and create a more complex application.

    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()

Creating Project in Eclipse

The contact manager application will use Maven for build and dependency management. For this we will use the Maven Dynamic Web Project in Eclipse as the base architecture of our application.

Download the below source code:
Maven Dynamic Web Project (6.7 KB)

spring3-hibernate-project-structureUnzip the source code to your hard drive and import the project in Eclipse. Once the project is imported in Eclipse, we will create package structure for Java source. Create following packages under src/main/java folder.

  • net.viralpatel.contact.controller – This package will contain Spring Controller classes for Contact Manager application.
  • net.viralpatel.contact.form – This package will contain form object for Contact manager application. Contact form will be a simple POJO class with different attributes such as firstname, lastname etc.
  • net.viralpatel.contact.service – This package will contain code for service layer for our Contact manager application. The service layer will have one ContactService interface and its corresponding implementation class
  • net.viralpatel.contact.dao – This is the DAO layer of Contact manager application. It consists of ContactDAO interface and its corresponding implementation class. The DAO layer will use Hibernate API to interact with database.

Entity Class – The Hibernate domain class

Let us start with the coding of Contact manager application. First we will create a form object or hibernate POJO class to store contact information. Also this class will be an Entity class and will be linked with CONTACTS table in database.
Create a java class Contact.java under net.viralpatel.contact.form package and copy following code into it.

File: src/main/java/net/viralpatel/contact/form/Contact.java

package net.viralpatel.contact.form;

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

public class Contact {
    private Integer id;
    private String firstname;

    private String lastname;

    private String email;
    private String telephone;
    public String getEmail() {
        return email;
    public String getTelephone() {
        return telephone;
    public void setEmail(String email) {
        this.email = email;
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    public String getFirstname() {
        return firstname;
    public String getLastname() {
        return lastname;
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    public void setLastname(String lastname) {
        this.lastname = lastname;
    public Integer getId() {
        return id;
    public void setId(Integer id) {
        this.id = id;

The first thing you’ll notice is that the import statements import from javax.persistence rather than a Hibernate or Spring package. Using Hibernate with Spring, the standard JPA annotations work just as well and that’s what I’m using here.

  • First we’ve annotated the class with @Entity which tells Hibernate that this class represents an object that we can persist.
  • The @Table(name = "CONTACTS") annotation tells Hibernate which table to map properties in this class to. The first property in this class on line 16 is our object ID which will be unique for all events persisted. This is why we’ve annotated it with @Id.
  • The @GeneratedValue annotation says that this value will be determined by the datasource, not by the code.
  • The @Column(name = "FIRSTNAME") annotation is used to map this property to the FIRSTNAME column in the CONTACTS table.

The Data Access (DAO) Layer

The DAO layer of Contact Manager application consist of an interface ContactDAO and its corresponding implementation class ContactDAOImpl. Create following Java files in net.viralpatel.contact.dao package.

File: src/main/java/net/viralpatel/contact/dao/ContactDAO.java

package net.viralpatel.contact.dao;

import java.util.List;

import net.viralpatel.contact.form.Contact;

public interface ContactDAO {
    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);

File: src/main/java/net/viralpatel/contact/dao/ContactDAOImpl.java

package net.viralpatel.contact.dao;

import java.util.List;

import net.viralpatel.contact.form.Contact;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

public class ContactDAOImpl implements ContactDAO {

    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {

    public List<Contact> listContact() {

        return sessionFactory.getCurrentSession().createQuery("from Contact")

    public void removeContact(Integer id) {
        Contact contact = (Contact) sessionFactory.getCurrentSession().load(
                Contact.class, id);
        if (null != contact) {


The DAO class in above code ContactDAOImpl implements the data access interface ContactDAO which defines methods such as listContact(), addContact() etc to access data from database.

Note that we have used two Spring annotations @Repository and @Autowired.

Classes marked with annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning. The @Component annotation is the main stereotype that indicates that an annotated class is a “component”.

The @Repository annotation is yet another stereotype that was introduced in Spring 2.0. This annotation is used to indicate that a class functions as a repository and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring’s DataAccessException hierarchy, even when using plain JPA in the DAO classes.

Another annotation used in ContactDAOImpl is @Autowired. This is used to autowire the dependency of the ContactDAOImpl on the SessionFactory.

The Service Layer

The Service layer of Contact Manager application consist of an interface ContactService and its corresponding implementation class ContactServiceImpl. Create following Java files in net.viralpatel.contact.service package.

File: src/main/java/net/viralpatel/contact/service/ContactService.java

package net.viralpatel.contact.service;

import java.util.List;

import net.viralpatel.contact.form.Contact;

public interface ContactService {
    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);

File: src/main/java/net/viralpatel/contact/service/ContactServiceImpl.java

package net.viralpatel.contact.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.form.Contact;

public class ContactServiceImpl implements ContactService {

    private ContactDAO contactDAO;
    public void addContact(Contact contact) {

    public List<Contact> listContact() {

        return contactDAO.listContact();

    public void removeContact(Integer id) {

In above service layer code, we have created an interface ContactService and implemented it in class ContactServiceImpl. Note that we used few Spring annotations such as @Service, @Autowired and @Transactional in our code. These annotations are called Spring stereotype annotations.

The @Service stereotype annotation used to decorate the ContactServiceImpl class is a specialized form of the @Component annotation. It is appropriate to annotate the service-layer classes with @Service to facilitate processing by tools or anticipating any future service-specific capabilities that may be added to this annotation.

Adding Spring MVC Support

Let us add Spring MVC support to our web application.

Update the web.xml file and add servlet mapping for org.springframework.web.servlet.DispatcherServlet. Also note that we have mapped url / with springServlet so all the request are handled by spring.

File: /src/webapp/WEB-INF/web.xml

Once the web.xml is configured, let us add spring-servlet.xml and jdbc.properties files in /src/main/webapp/WEB-INF folder.
File: /src/main/webapp/WEB-INF/jdbc.properties

The jdbc.properties file contains database connection information such as database url, username, password, driver class. You may want to edit the driverclass and dialect to other DB if you are not using MySQL.

Oracle Properties

In case you are using Oracle database, you can modify the jdbc properties and have oracle related dialect and other properties:

File: /src/main/webapp/WEB-INF/spring-servlet.xml

The spring-servlet.xml file contains different spring mappings such as transaction manager, hibernate session factory bean, data source etc.

  • jspViewResolver bean – This bean defined view resolver for spring mvc. For this bean we also set prefix as “/WEB-INF/jsp/” and suffix as “.jsp”. Thus spring automatically resolves the JSP from WEB-INF/jsp folder and assigned suffix .jsp to it.
  • messageSource bean – To provide Internationalization to our demo application, we defined bundle resource property file called messages.properties in classpath.
    Related: Internationalization in Spring MVC
  • propertyConfigurer bean – This bean is used to load database property file jdbc.properties. The database connection details are stored in this file which is used in hibernate connection settings.
  • dataSource bean – This is the java datasource used to connect to contact manager database. We provide jdbc driver class, username, password etc in configuration.
  • sessionFactory bean – This is Hibernate configuration where we define different hibernate settings. hibernate.cfg.xml is set a config file which contains entity class mappings
  • transactionManager bean – We use hibernate transaction manager to manage the transactions of our contact manager application.

File: /src/main/resources/hibernate.cfg.xml

File: /src/main/resources/messages_en.properties

Spring MVC Controller

We are almost done with our application. Just add following Spring controller class ContactController.java to net.viralpatel.contact.controller package.

File: /src/main/java/net/viralpatel/contact/controller/ContactController.java

package net.viralpatel.contact.controller;

import java.util.Map;

import net.viralpatel.contact.form.Contact;
import net.viralpatel.contact.service.ContactService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class ContactController {

	private ContactService contactService;

	public String listContacts(Map<String, Object> map) {

		map.put("contact", new Contact());
		map.put("contactList", contactService.listContact());

		return "contact";

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact")
	Contact contact, BindingResult result) {


		return "redirect:/index";

	public String deleteContact(@PathVariable("contactId")
	Integer contactId) {


		return "redirect:/index";

The spring controller defines three methods to manipulate contact manager application.

  • listContacts method – This method uses Service interface ContactServer to fetch all the contact details in our application. It returns an array of contacts. Note that we have mapped request “/index” to this method. Thus Spring will automatically calls this method whenever it encounters this url in request.
  • addContact method – This method adds a new contact to contact list. The contact details are fetched in Contact object using @ModelAttribute annotation. Also note that the request “/add” is mapped with this method. The request method should also be POST. Once the contact is added in contact list using ContactService, we redirect to /index page which in turn calls listContacts() method to display contact list to user.
    Related: Forms in Spring MVC
  • deleteContact method – This methods removes a contact from the contact list. Similar to addContact this method also redirects user to /index page once the contact is removed. One this to note in this method is the way we have mapped request url using @RequestMapping annotation. The url “/delete/{contactId}” is mapped thus whenever user send a request /delete/12, the deleteCotact method will try to delete contact with ID:12.

Finally add following JSP file to WEB-INF/jsp folder.

File: /src/main/webapp/WEB-INF/jsp/contact.jsp

Download Source code

Spring3MVC_Hibernate_Maven.zip (16 KB)

That’s All folks

Compile and execute the Contact manager application in Eclipse.

If you read this far, you should follow me on twitter here.