Spring Hibernate End to End Integration using Maven, Spring MVC, JSP, Oracle11g : A Step by Step Guide

This post aims at giving a start-up point while you begin understanding the Spring-Hibernate integration and would like to start trying it out using a practical implementation  like me. I am using Maven 3, Oracle11g (with a set-up guide including creating a user and a table) , Spring 3.0, Hibernate 3.6 and STS as the development IDE.

The agenda of the post is:

1. Setup DB Layer (Oracle11g)
2. Creating a Maven Project and adding Hibernate Layer
3. Spring Hibernate Integration including Spring MVC

Setup DB Layer (Oracle11g)

To begin with, If you don’t have Oracle already Installed or you need some reference setting up a User or a Table, Visit this Blog Post. We will be using the same table and DB url mentioned in this post to connect it using Spring and Hibernate.

We have used the following Script to generate an “orders” table to connect with.

create table orders (
order_id   number primary key,
order_dt   date,
order_type varchar2(50),
customer_name varchar2(50)

Once we are ready with our database and aquire the connection URL, we can move to adding the middleware.

Creating a Maven Project and adding Hibernate Layer

Step 1. Setup Maven (refer http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html)
If have maven already installed, skip this step.

Step 2. Go to Eclipse/STS, Create a new maven Project as:
New -> Other -> Type maven and select New Maven Project
Check “Select a Simple Project”, Click Next
Enter Group Id:com.codeyard
Artifact Id: ordermanager
packaging: war
Name: HelloHibernate

Step 3. Add hibernate and Oracle driver dependencies to your pom.xml so that it looks like:

<project xmlns="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a>" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"
xsi:schemaLocation="<a href="http://maven.apache.org/POM/4.0.0">http://maven.apache.org/POM/4.0.0</a> <a href="http://maven.apache.org/xsd/maven-4.0.0.xsd">http://maven.apache.org/xsd/maven-4.0.0.xsd</a>">
<!-- ORACLE JDBC driver, need install yourself -->


I got the following error while adding ojdbc6.jar dependency into my POM:
24/7/12 11:57:05 AM IST: Missing artifact com.oracle:ojdbc6:jar:11.2.0:compile
The POM for com.oracle:ojdbc6:jar:11.2.0 is missing, no dependency information available
Failed to execute goal on project Maven: Could not resolve dependencies … Could not find artifact com.oracle:ojdbc6:jar ….

I could only resolved it by manually installing a copy of the jar in the local repository as:
To manually deploy the Oracle JDBC driver to your local repository type the following:

mvn install:install-file -Dfile={ORACLE_HOME}/jdbc/lib/ojdbc6.jar -Dpackaging=jar\
-DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0
where {ORACLE_HOME} is the path to the Oracle Database installation.


Download ojdbc6.jar from Oracle website, place it on your local machine and type the following:

mvn install:install-file -Dfile=C:/jdbc6.jar -Dpackaging=jar\
-DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0

If anyone could do it in a better way, please share.(uploading the jar into a central repo like Nexus and refering it from there is another workaround).

Step 4. Create a class for Order in package  com.codeyard.order named Order.java src/main/resources/com/codeyard/order

 package com.codeyard.order;

 import java.util.Date;

 public class Order implements java.io.Serializable{

 private static final long serialVersionUID = 1L;

 private int orderId;
 private String OrderType;
 private String customerName;
 private Date OrderDate;

 public Order() {

 public Order(int orderId, String OrderType, String customerName, Date OrderDate) {

 public int getOrderId() {
     return orderId;

 public void setOrderId(int orderId) {
 this.orderId = orderId;

 public String getOrderType() {
     return OrderType;

 public void setOrderType(String orderType) {
     OrderType = orderType;

 public String getCustomerName() {
     return customerName;

 public void setCustomerName(String customerName) {
     this.customerName = customerName;

 public Date getOrderDate() {
     return OrderDate;

 public void setOrderDate(Date orderDate) {
     OrderDate = orderDate;


Step 5. Create a mapping file for hibernate to map your java object to DB entity.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"<a href="http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd</a>">
<class name="com.codeyard.order.Order" table="ORDERS">
<id name="orderId" type="int">
    <column name="ORDER_ID" precision="5" scale="0" />
<generator />
<property name="OrderType" type="string">
    <column name="ORDER_TYPE" length="20" not-null="true" />
<property name="customerName" type="string">
    <column name="CUSTOMER_NAME" length="20" not-null="true" />
<property name="OrderDate" type="date">
    <column name="ORDER_DT" length="7" not-null="true" />

Step 6. Add hibernate.cfg.xml under src/main/recources as:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:P24</property>
 <property name="hibernate.connection.username">testconn</property>
 <property name="hibernate.connection.password">testconn</property>
 <property name="hibernate.default_schema">testconn</property>
 <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
 <property name="show_sql">true</property>

 <!-- add mapping to *.hbm.xml file here -->
 <mapping resource="com/codeyard/order/order.hbm.xml"></mapping>
 <!-- <mapping class="com.codeyard.model.AdvanceOrder" /> -->

Step 7. Create a test class to test if you are able to insert data in order table.

I am using junit4 and for that you need to add the following dependency in pom.xml


Add a java test case in the src/test/java/com/codeyard/hibernate package.

package com.codeyard.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.codeyard.order.Order;

public class OrderTest {
SessionFactory sessionFactory;

public void init() {
try {
  sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
  System.err.println("Failed to create session factory." + ex);
  throw new ExceptionInInitializerError(ex);

public void after() {

public void testOrderCreation(){

  Session session = sessionFactory.openSession();

  Order order = new Order();

  order.setOrderDate(new Date());




Running this testcase results in the following error on console:

Failed to create session factory.org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

To resolve this, I added the following dependency of java assist:

Rerun the test case and you should see the following message on console :

Hibernate: insert into testconn.ORDERS (ORDER_TYPE, CUSTOMER_NAME, ORDER_DT, ORDER_ID) values (?, ?, ?, ?)
Row added


Now open Sql Developer ad refresh the table, you should see the newly added data through test case in the table.

Spring MVC and Hibernate

Now, we make this project a little advance by having Spring in place and integrating Hibernate to it.

Step1. Add the following Spring and ORM Dependencies in your POM.xml for spring-hibernate integration.




Step 2.  Add a separate AdvanceOrder.java class. we shall map this class in package com.codeyard.model to the same ORDERS Table used previously. We will do the mapping with the help of Spring annotations and will not require any .hbm.xml mapping file anymore.

package com.codeyard.model;

import java.util.Date;

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

@Table(name = "ORDERS")
public class AdvanceOrder {

 @SequenceGenerator(name = "OrderSequence", sequenceName = "ORDER_SEQ", allocationSize = 5, initialValue = 1)
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "OrderSequence")
 @Column(name = "ORDER_ID")
 private int orderId;

 @Column(name = "ORDER_TYPE")
 private String orderType;

 @Column(name = "CUSTOMER_NAME")
 private String customerName;

 @Column(name = "ORDER_DT")
 private Date orderDate;

 public int getOrderId() {
 return orderId;

public void setOrderId(int orderId) {
 this.orderId = orderId;

public String getOrderType() {
 return orderType;

public void setOrderType(String orderType) {
 this.orderType = orderType;

public String getCustomerName() {
 return customerName;

public void setCustomerName(String customerName) {
 this.customerName = customerName;

public Date getOrderDate() {
 return orderDate;

public void setOrderDate(Date orderDate) {
 this.orderDate = orderDate;


Uncomment the entry for AdvanceOrder mapping in hibernate.cfg.xml: <mapping />

Step 3.  Add DAO Layer by introducing OrderDAO interface and corresponding OrderImpl class in com.codeyard.dao package as:


package com.codeyard.dao;
import java.util.List;
import com.codeyard.model.AdvanceOrder;

public interface OrderDao {

   public void createOrder(AdvanceOrder order);
   public List<AdvanceOrder> getAllOrders();
   public void deleteOrder(Integer id);


package com.codeyard.dao;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.codeyard.model.AdvanceOrder;

public class OrderImpl implements OrderDao {

 private SessionFactory sessionFactory;

public void createOrder(AdvanceOrder order) {


public List<AdvanceOrder> getAllOrders() {
 return sessionFactory.getCurrentSession().createQuery("from AdvanceOrder").list();

public void deleteOrder(Integer id) {
 AdvanceOrder order = (AdvanceOrder) sessionFactory.getCurrentSession()
 .load(AdvanceOrder.class, id);
 if (null != order) {



Step 4. Add service layer by introducing OrderService.java and corresponding OrderServiceImpl.java in com.codeyard.service package as:


package com.codeyard.service;
import java.util.List;
import com.codeyard.model.AdvanceOrder;

public interface OrderService {

  public void createOrder(AdvanceOrder contact);
  public List<AdvanceOrder> getAllOrders();
  public void deleteOrder(Integer id);



package com.codeyard.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.codeyard.dao.OrderDao;
import com.codeyard.model.AdvanceOrder;

public class OrderServiceImpl implements OrderService {

 private OrderDao orderDAO;

 public void createOrder(AdvanceOrder contact) {

 public List<AdvanceOrder> getAllOrders() {
   return orderDAO.getAllOrders();

 public void deleteOrder(Integer id) {


crete a sequecne in Oracle by running the following command using SQL Developer:
create sequence ORDER_SEQ start with 1 INCREMENT BY 2;
Step 5.Add Spring MVC and some more Dependencies.






Step 6.  Create OrdersController.java in com.codeyard.controller to entertain your http requests.

package com.codeyard.controller;

import java.util.Map;
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;
import com.codeyard.model.AdvanceOrder;
import com.codeyard.service.OrderService;

public class OrdersController {
 private OrderService orderService;

 @RequestMapping(value = "/list", method = RequestMethod.GET)
 public String listContacts(Map<String, Object> map) {
    map.put("order", new AdvanceOrder());
    map.put("orderList", orderService.getAllOrders());
    return "order";

 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public String addContact(@ModelAttribute("order") AdvanceOrder order, BindingResult result) {
    return "redirect:/orders/list";

 public String deleteContact(@PathVariable("orderId") Integer orderId) {
    return "redirect:/orders/list";

Step 7.Add View Layer.As you can see in the above step, we have used the views and model passed along with the view. We need to have appropriate view (jsp) and view resolver in the spring context file. Our WEB-INF/web.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">

We have used the servlet name as codeyard, Spring will look for the context file named codeyard-context.xml under WEB-INF folder which in this case, looks like:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
 http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
 <context:component-scan base-package="com.codeyard" />

 <bean id="jspViewResolver"
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/jsp/" />
 <property name="suffix" value=".jsp" />

<bean id="messageSource"
 <property name="basename" value="classpath:messages" />
 <property name="defaultEncoding" value="UTF-8" />
 <bean id="propertyConfigurer"
 p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
 destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
 p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

 <bean id="sessionFactory"
 <property name="dataSource" ref="dataSource" />
<property name="configLocation">
 <property name="configurationClass">
 <property name="hibernateProperties">
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>

<tx:annotation-driven />

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

you can see, we have used reference to jdbc properties file for obtaining DB connections, here is our jdbc.properties file lying under WEB-INF folder

jdbc.driverClassName= oracle.jdbc.driver.OracleDriver

We can get rid of the connection related attributes in hibernate.cfg.xml as we can fetch then using properties file now. Add order.jsp.

WEB-INF -> jsp -> order.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 <title>Spring Hibernate Sample Orders</title>

<h2>Log Order Details</h2>

<form:form method="post" action="save.html" commandName="order">

    <td><form:label path="OrderType">Order Type</form:label></td>
    <td><form:input path="OrderType" /></td>
    <td><form:label path="customerName">Customer Name</form:label></td>
    <td><form:input path="customerName" /></td>
    <td><form:label path="orderDate">Order Data</form:label></td>
    <td><form:input path="orderDate" /></td>

 <td colspan="2">
   <input type="submit" value="Add Order"/>

<h3>Order History</h3>
<c:if test="${!empty orderList}">
  <th>Customer Name</td>
  <th>Order Date</td>
  <th>Order Date</td>
<c:forEach items="${orderList}" var="order">
    <td><a href="delete/${order.orderId}">delete</a></td>


Step 8. run mvn clean install from your project’s directory in command prompt. It should results in build success. Copy the ordermanager-0.0.1-SNAPSHOT.war in your tomcat/webapps directory, start the server.

use the url as http://localhost:8080/contextpath/urlpattern/path mentioned in controller

eg: http://localhost:8080/ordermanager-0.0.1-SNAPSHOT/orders/list.

and try the application..  DOWNLOAD SOURCE PART 2.ZIP

About these ads

About Richa Jain
Java / J2EE / UI Developer. Likes to work in Agile way

9 Responses to Spring Hibernate End to End Integration using Maven, Spring MVC, JSP, Oracle11g : A Step by Step Guide

  1. Hmm is anyone else experiencing problems with the images on this blog loading?
    I’m trying to determine if its a problem on my end or if it’s the
    blog. Any feed-back would be greatly appreciated.

  2. Ankush says:

    Thanks For this tutorial. Really helped to get through the basics.

  3. b0romir says:

    Great tutorial, really well explained. I’m a PHP programmer and I’m starting my adventure with JAVA. Could you explain me what is the purpose of using service class if all what it’s doing is calling dao methods?

  4. Imad says:

    thanks for this tuto it’s very clear but Spring will look for the context file named codeyard-servlet.xml under WEB-INF not codeyard-context.xml ;)

  5. mahesh says:


    i am getting the following error. Can you please help me out on running?

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘ordersController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.codeyard.service.OrderService com.codeyard.controller.OrdersController.orderService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘orderServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.codeyard.dao.OrderDao com.codeyard.service.OrderServiceImpl.orderDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘orderImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.codeyard.dao.OrderImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/codeyard-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ‘configurationClass’ of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property ‘configurationClass’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)


  6. mak says:


    Great tutorial, but i got some question.

    1) how welcome file mentioned i.e list.html calls orders.jsp ?

    2) I had used mvn jetty:run command to run the application and opened the page through url http://localhost:8080/orders/list

    I would like to know how the url is formed, since i expected it to run with a project name.

    Thanks in advance.

    • Richa Jain says:

      Hello, The URL is formed as

      htt p: // [ip]:[port]/
      [contextpath]/[path mentioned in URL pattern("/" is used in this example)]
  7. You can certainly see your expertise within the article you write.
    The world hopes for more passionate writers like you who aren’t afraid to say how they believe. Always go after your heart.

  8. inayatullah says:

    Good Example. I have downloaded and just created a sequence additionally and it worked fine for me. Any how thanks for assisting us with a good example – Inayatullah.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: