Steps to Get Started with Spring MVC 4 & Hibernate 4

The article lists down steps one need to take in order to get up and running with Spring MVC 4 and Hibernate 4. The article will describe following three key aspects:

  • General configurations to setup Java, Eclipse and Tomcat Server
  • Spring MVC 4 configurations & code samples
  • Hibernate 4 configurations & code samples

Following are key components/artifacts that would be required to create the web application which makes use of Spring MVC 4 for managing MVC and Hibernate as an ORM framework:

  • Libraries & Tools
  • Configuration files
  • Components
    1. Controller
    2. Views (JSP pages)
    3. Business logic classes
    4. Data access classes
Key Libraries & Tools

Following are key libraries and tools to download and get ready before start working apart from Java (used Java 7) :

  • Libraries
    1. Spring MVC and related libraries (currently at version 4.0.3)
    2. Spring dependent libraries such as following:
      • Commons-logging jar file
    3. Hibernate libraries (currently at version 4.3.5)
  • Tools/Softwares
    1. Eclipse JavaEE Kepler
    2. Tomcat server (currently at version 8)
    3. A database such as MySQL


Key Configuration Files

Following are minimum required configuration files you would need to add in the WEB-INF folder:

  1. web.xml
  2. spring-servlet.xml (assuming you named dispatcher servlet in web.xml as “spring”)
  3. hibernate.cfg.xml


Note some of the following XML blocks in the code below:

  • Spring configuration (Dispatcher Servlet)
  • CSS/JS files
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
id="WebApp_ID" version="3.1">

<!-- Spring Configuration -->


<!-- Config for accessing JS/CSS files from with JSP files -->



<beans xmlns=""
xmlns:xsi="" xmlns:p=""

<!-- Configuration describing the package consisting of all components -->

<context:component-scan base-package="com.vf.restaurants" />

<!-- Configuration defining views files -->

<property name="prefix">
<property name="suffix">

<!-- Database-related Configuration to connect with database -->

<bean id="dataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/docdb"
p:username="root" p:password="root" />

<!-- Hibernate-related Configuration -->

<bean id="sessionFactory"
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<property name="hibernateProperties">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>

<!-- Transaction related configuration for working with database -->

<tx:annotation-driven />
<bean id="transactionManager"
<property name="sessionFactory" ref="sessionFactory" />



<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

<mapping class="com.vf.restaurants.Doctor" />


Configuration Steps

Following are different steps (in detail) which would help you get up and running. General Configurations (Requisites)

  • Download all the libraries and tools as mentioned above.
  • Execute hello world in eclipse and make sure your Java and Eclipse installation is properly installed and configured.
  • Make sure you have added Tomcat 8 server in the server tab that could be found in eclipse work bench. Configure as per following page to make sure you could start and stop the Tomcat from within eclipse. This is just for the ease of development in terms of quickly starting and stopping the server from within eclipse.
  • Create a Dynamic Web Project namely, HelloDynWebProject, using eclipse. Create an index.jsp within WEB-INF folder. Print “helloworld” using index.jsp from a url after you started server from servers tab. The URL could look something like http://localhost:8080//. This can be done by right clicking on project and selecting Run as…Run on Server. This confirms that your Java, eclipse and Tomcat is working fine. Move to next step.
  • Copy and paste spring and hibernate libraries along with dependent libraries within folder, WEB-INF/lib.

Spring MVC Configuration & Code Samples

Before I go ahead describing several code samples & configurations, lets look at following diagram that describes request-response flow between views (JSPs pages) and controller classes.


Before representing the classes and describing them, lets take a look at the view, the hello.jsp file. Following is the code:


<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<ul class="nav nav-list">
<li class="nav-header">Services</li>
<li class="active"><a href="#">New Restaurant</a></li>
<div class="span10">
<form class="form-horizontal" method="post" action="/HelloDynWebProject/createdoc">
<legend>New Doctor</legend>
<input type="text" name="name" placeholder="">
<input type="text" name="address" placeholder="">
<div class="control-group" style="padding-top:20px">
<button type="submit" class="btn">Submit</button>


After creating view file, create the controller class and related components (typical ones) such as following:

  • NewDoctorController
  • NewDoctor
  • Doctor
  • DoctorDAO


Pay attention to some of the following (primarily annotations) in the controller class code such as @Controller, @AutoWired. For now, you could add a dummy method addDoctor in DoctorDAO to complete the flow.

public class NewDoctorController {

	private NewDoctor newDoc;

	@RequestMapping(value = "/newdoc", method = RequestMethod.GET)
	public ModelAndView createDoctor( ModelMap model ) {
		return new ModelAndView("hello");

	@RequestMapping(value = "/createdoc", method = RequestMethod.POST)
	public String createNewDoctor(Doctor doctor, ModelMap model) {

		model.addAttribute("message", "Spring 3 MVC Hello World");
		return "hello";




Doctor class acts as a domain object that also maps to the database table which we will look into Hibernate section. Pay attention to following annotations.

@Table(name = "doctor")
public class Doctor {

    private Integer id;

	private String address;

	private String name;

	public Integer getId() {
		return id;
	public void setId(Integer id) { = id;
	public String getAddress() {
		return address;
	public void setAddress(String address) {
		this.address = address;
	public String getName() {
		return name;
	public void setName(String name) { = name;



This is a class consisting of business logic. Pay attention to @Component and @AutoWired annotation.

public class NewDoctor {

	private DoctorValidation docVal;
	private DoctorDAO  docDAO;

	public NewDoctor() {		

	public DocResult addDoctor( Doctor doc ) {
		DocResult docResult = new DocResult();
		if( docVal.validated( doc ) ) {
			if( docDAO.persist( doc ) ) {
				docResult.setSuccess( true );
				docResult.setMessage( "success");
		return docResult;

	public DoctorValidation getDocVal() {
		return docVal;

	public void setDocVal(DoctorValidation docVal) {
		this.docVal = docVal;

	public DoctorDAO getDocDAO() {
		return docDAO;

	public void setDocDAO(DoctorDAO docDAO) {
		this.docDAO = docDAO;


Once done adding above classes, go ahead and deploy the application. I would rather suggest you to do Debug as…Debug on Server and verify the request-response flow across different classes. Access the application at following link: http://localhost:8080/hellodynwebproject/newdoc. Enter the inputs and submit.

Hibernate Configuration & Code Samples

Following diagram represents two key aspects of hibernate configurations which is XML definitions for hibernate and mapping definitions (objects representing tables)

hibernate configurations

Add the hibernate.cfg.xml file (code shown above) within WEB-INF folder.  Create a database with name as “docdb” and add following table:

`name` varchar(100) NOT NULL,
`address` varchar(200) NOT NULL,


Create DoctorDAO class. Pay attention to annotations such as @Component, @Transactional and @Autowired.

public class DoctorDAO {

    private SessionFactory sessionFactory;

	public boolean persist(Doctor doc) {
		return true;


Once done with above coding and db creation, redeploy and test the application at http://localhost:8080/hellodynwebproject/newdoc. Add name and address and submit. Check if the data got added in the database.


Source Code for HelloDynWebProject

That is it! Let me know if you were able to get up and running using this article. Also, following is the link to download the eclipse project consisting of source code and config files. You may want to download Spring (& dependent) jars and Hibernate jars and put under WEB-INF/lib.

Source code for HelloDynWebProject


Ajitesh Kumar
Follow me

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog,
Posted in Java. Tagged with .

Leave a Reply

Your email address will not be published. Required fields are marked *