Spring 4 and Hibernate 4 Integration example project in Eclipse without maven support

In this tutorial we are going to see the steps to integrate Hibernate 4 with Spring 4 MVC framework without maven support. If you are new to Spring framework, you can have a look at my earlier tutorial how to start new spring application. In this project, let us develop an demo application for Adding/ Editing/ Deleting/ Listing Items in Inventory using MySQL database with Spring and Hibernate support.

Technologies used in this application :

1. Spring 4+ 
2. Hibernate 4.3.6
3. JDK 1.8.0
4. Eclipse (Kepler)

Please have a look at the below image that shows all the required spring 4+ and hibernate 4.3.6 jars.

Spring Hibernate Project Structure Part1Spring Hibernate Project Structure Part2

Now let us see the steps

Step 1: Create a dynamic project (in our example : SpringHibernateDemo) in Ecplise (File->New -> Dynamic Web Project)

Step 2: Copy all the jars to your class path (lib folder)

Step 3: Decide database, table and necessary fields for your demo application (Database: test, Table: ItemsMaster, Fields Used : item_code, item_name, price, quantity , createdOn )

Query to create the above table : CREATE TABLE ItemsMaster (item_code int NOT NULL AUTO_INCREMENT PRIMARY KEY, item_name varchar(50) DEFAULT NULL, price decimal DEFAULT 0, qty int DEFAULT 0, create on timestamp);

Step 4: Create Hibernate Configuration file (hibernate-cfg.xml) for configuring database connections (In our example, we are going to work with the MySql database “test”)

hibernate-cfg.xml


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

   	<session-factory>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/test
		</property>

		<property name="connection.pool_size">1</property>

		<!-- SQL dialect -->
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>

		<!-- Enable Hibernate's automatic session context management -->
		<property name="current_session_context_class">thread</property>

		<!-- Disable the second-level cache  -->
		<property name="cache.provider_class">
			org.hibernate.cache.NoCacheProvider
		</property>

		<!-- Display all generated SQL to stdout -->
		<property name="show_sql">true</property>

		<mapping class="net.javaonline.spring.product.dto.ItemMaster" />

	</session-factory>

</hibernate-configuration> 

Please note that the mapping class. ItemMaster is the persistent class for storing item details.

 

Step 5: Create persistent class (ItemMaster) (Simple Java bean (POJO) class ) for mapping the table (ItemsMaster) fields using JPA (Java Persistent Annotations). The whole Persistent (POJO) class is defined as an Entity which can be done using @Entity annotation in the beginning of the class. Mapping can also be done without java annotations i.e. using java bean + hibernate.hbm.xml.

ItemMaster.java

package net.javaonline.spring.product.dto;

import java.io.Serializable;

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

import java.util.Date;

@Entity
@Table(name="ItemsMaster")
public class ItemMaster implements Serializable{

	private static final long serialVersionUID = 453693552059515150L;
	private Long item_code;
	private String item_name;
	private double price  ;
	private int qty;
	@Temporal(TemporalType.DATE)
	@Column (name="createdOn")
	private Date createdOn;

public Date getCreatedOn() {
		//return new Date();
		return createdOn;
	}
	public void setCreatedOn(Date createdOn) {
		this.createdOn = createdOn;
	}

	@Id
	@GeneratedValue
	@Column(name="item_code")
	public Long getItem_code() {
		return item_code;
	}
	public void setItem_code(Long item_code) {
		this.item_code = item_code;
	}
	@Column(name="item_name")
	public String getItem_name() {
		return item_name;
	}
	public void setItem_name(String item_name) {
		this.item_name = item_name;
	}

	@Column(name="price")
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Column(name="qty")
	public int getQty() {
		return qty;
	}
	public void setQty(int qty) {
		this.qty = qty;
	}

} 

Note : Hibernate even can directly access the fields without getter and setter methods. But it is always recommended to create getter setter methods.

Step 6: Add DispatcherServlet to web.xml so that all the requests are routed through org.springframework.web.servlet.DispatcherServlet

web.xml

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

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

  <servlet>
    <servlet-name>inventory</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>inventory</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

Step 7: Configure inventory-servlet.xml to create various beans

1. ViewResolver

2. DataSource

3. SessionFactory

4. TransactionManager

5. DAO Class

inventory-servlet.xml

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

    <context:component-scan base-package="net.javaonline.spring.product.controller, net.javaonline.spring.product.dao" />

    <bean id="itemMasterDao" class="net.javaonline.spring.product.dao.ItemMasterDAOImpl">
    	<constructor-arg>
        	<ref bean="sessionFactory" />
    	</constructor-arg>
	</bean>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="j123456" />
    </bean>

    <bean id="sessionFactory"    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager"   class="org.springframework.orm.hibernate4.HibernateTransactionManager">
           <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/Pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans> 

Step 8: Add Web Controller to the project so that all the requests are mapped here to perform various operations such as add, edit, delete, update, etc.. and transform into model.

inventory-servlet.xml

package net.javaonline.spring.product.controller;

import java.util.List;

import net.javaonline.spring.product.dao.ItemMasterDAO;
import net.javaonline.spring.product.dto.ItemMaster;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ProductController {

	@Autowired
	private ItemMasterDAO itemMasterDao; 

	  @RequestMapping(value="/list")
	    public ModelAndView list() {
	        List<ItemMaster> itemList = itemMasterDao.list();
	        ModelAndView model = new ModelAndView("ItemMasterList");
	        model.addObject("itemList", itemList);
	        return model;
	    }

	  @RequestMapping(value="/loadAddForm")
	    public ModelAndView add() {
	        ModelAndView model = new ModelAndView("ItemMasterAdd");
		   ItemMaster item=new ItemMaster();
           model.addObject("item", item);
	        List<ItemMaster> itemList = itemMasterDao.list();
	        model.addObject("itemList", itemList);
	        return model;
	    }

	  @RequestMapping(value="/edit")
	    public ModelAndView edit(@RequestParam(value="id", required=true) Long id) {
		  System.out.println("Id= " + id);
	        ModelAndView model = new ModelAndView("ItemMasterAdd");
		   ItemMaster item=  itemMasterDao.getItem(id);
           model.addObject("item", item);
	       List<ItemMaster> itemList = itemMasterDao.list();
	        model.addObject("itemList", itemList);
	        return model;
	    }

	  @RequestMapping(value="/delete")
	    public ModelAndView delete(@RequestParam(value="id", required=true) Long id) {
	        ModelAndView model = new ModelAndView("ItemMasterAdd");
	        itemMasterDao.delete(id);
	       List<ItemMaster> itemList = itemMasterDao.list();
	        model.addObject("itemList", itemList);
	        return model;
	    }

	  @RequestMapping(value = "/save", method = RequestMethod.POST)
	    public ModelAndView save(@ModelAttribute("item") ItemMaster item) {
	        System.out.println(item.getItem_name());
	        if(null != item )
	        	itemMasterDao.add(item);

	        ModelAndView model = new ModelAndView("ItemMasterAdd");
			item=new ItemMaster();
	        model.addObject("item", item);
	        List<ItemMaster> itemList = itemMasterDao.list();
	        model.addObject("itemList", itemList);
	        return model;
	  }

	  @RequestMapping(value = "/update", method = RequestMethod.POST)
	    public ModelAndView update(@ModelAttribute("item") ItemMaster item) {
	        System.out.println(item.getItem_name());
	        if(null != item )
	        	itemMasterDao.update(item);

	        ModelAndView model = new ModelAndView("ItemMasterAdd");
			item=new ItemMaster();
	        model.addObject("item", item);
	        List<ItemMaster> itemList = itemMasterDao.list();
	        model.addObject("itemList", itemList);
	        return model;
	  }

} 

Step 9: DAO Class and its Implementation

ItemMasterDAO.java

package net.javaonline.spring.product.dao;

import java.util.List;

import net.javaonline.spring.product.dto.ItemMaster;

public interface ItemMasterDAO {

	public List<ItemMaster> list();
	public void add(ItemMaster item);
	public void  update(ItemMaster item);
	public ItemMaster  getItem(Long id);
	public void  delete(Long id);

}

ItemMasterDAOImpl.java

All database operations such as add, list, delete, update using Hibernate are implemented here.

package net.javaonline.spring.product.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import net.javaonline.spring.product.dto.ItemMaster;

@Transactional
public class ItemMasterDAOImpl implements ItemMasterDAO {

	 private SessionFactory sessionFactory;

	    public ItemMasterDAOImpl(SessionFactory sessionFactory) {
	        this.sessionFactory = sessionFactory;
	    }

    @Override
	public void add(ItemMaster item) {
		Session session = sessionFactory.getCurrentSession();
		try {
			session.beginTransaction();
			session.save(item);
		  } catch (HibernateException e) {
			  e.printStackTrace();
			  session.getTransaction().rollback();
		}
			session.getTransaction().commit();
	}

    @Override
	public void update(ItemMaster item) {

		Session session = sessionFactory.getCurrentSession();
		try {
			System.out.println("IN Update");
			session.beginTransaction();
			session.saveOrUpdate(item);
			} catch (HibernateException e) {
				e.printStackTrace();
				session.getTransaction().rollback();
			}
		session.getTransaction().commit();
	}

	@Override
	public ItemMaster getItem(Long id) {
		Session session = sessionFactory.getCurrentSession();
		ItemMaster item=null;
		try {
			System.out.println("IN GetIteam");
			session.beginTransaction();
		    item = (ItemMaster) session.get(ItemMaster.class, id);
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return item;
	}

	@Override
	public void delete(Long id) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		ItemMaster item = (ItemMaster) session.get(ItemMaster.class, id);
		if(null != item) {
			session.delete(item);
		}
		session.getTransaction().commit();
		//return item;
	}

	@Override
	public List<ItemMaster> list() {

		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		List<ItemMaster> items = null;
		try {
			System.out.println("IN LIST");
			items = (List<ItemMaster>)session.createQuery("from ItemMaster").list();

		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return items;
	}

}

Step 10: Now let us create view (JSP pages) for the project.

ItemMasterAdd.jsp -> For adding, editing, and deleting item

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Add Item</title>

 <script  type ="text/javascript">

   function update()
	{
	document.productForm.action="update.do";
	document.productForm.submit();

	}

   function list()
	{
	document.productForm.action="list.do";
	document.productForm.submit();

	}

</script>
    </head>

    <body>

    <form:form name="productForm" method="post" action="save.do" modelAttribute="item">
    <input name="item_code" type="hidden" value="${item.item_code}">
        <div align="center">
            <h1>Item Detail</h1>
            <table border="1">

                <tr>
                       <th>Item Name</th>   <td> <input name="item_name" value="${item.item_name}"></td>

                </tr>
             <tr>
                       <th>Price</th>   <td> <input name="price" value="${item.price}"></td>

                </tr>
             <tr>
                       <th>Quantity</th>   <td> <input name="qty" value="${item.qty}"></td>

                </tr>
               <tr>
                       <th> <input type="submit" value="Add New Item">   </th>   <th>   <input type="button" value="Update"  onclick="update()"/> <input type="button" value="List"  onclick="list()"/></th> 

                </tr>

            </table>
        </div>

        </form:form>

         <div align="center">
            <h1>Item List</h1>
            <table border="1">
            <tr>
                <th>S.No.</th>
                <th>Item Code</th>
                <th>Item Name</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Action</th>
                <th>Action</th>

                 </tr>
                <c:forEach var="item" items="${itemList}" varStatus="status">
                <tr>
                    <td>${status.index + 1}</td>
                    <td>${item.item_code}</td>
                    <td>${item.item_name}</td>
                    <td>${item.price}</td>
                    <td>${item.qty}</td>
                    <td><a href="edit.do?id=${item.item_code}">Edit</a></td>
    				<td><a href="delete.do?id=${item.item_code}">Delete</a></td>  

                </tr>
                </c:forEach>
            </table>
        </div>             

    </body>
</html>

ItemMasterList.jsp -> For Listing the items.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home</title>
    </head>
    <body>
        <div align="center">
            <h1>Item List</h1>
            <table border="1">
            <tr>
                <th>S.No.</th>
                <th>Item Code</th>
                <th>Item Name</th>
                <th>Price</th>
                <th>Quantity</th>
              </tr>  

                <c:forEach var="item" items="${itemList}" varStatus="status">
                <tr>
                    <td>${status.index + 1}</td>
                    <td>${item.item_code}</td>
                    <td>${item.item_name}</td>
                    <td>${item.price}</td>
                    <td>${item.qty}</td>

                </tr>
                </c:forEach>
            </table>
        </div>
    </body>
</html>

Run the above application using http://localhost:8080/SpringHibernateDemo/loadAddForm.do

1. Adding Pears Item

Spring Hibernate Inpute screen

2. Editing Quantity of CINTHOL from 20 to 90.

Spring Hibernate edit screen2

 

Click on edit link to do changes.  Click on update to save the changes.

 

3. After Updation

Spring Hibernate After edit screen

4. Listing the Items by clicking List button.

Spring Hibernate After list screen

 

Reference : Spring Hibernate Integration

You can download the above project including Jars here Download

Leave a Reply