Spring Hibernate Integration

In this post we will be discussing on Spring Hibernate integration. As we all know Spring provides an ORM support and one of the best available ORM tool to be integrated with Spring is Hibernate. The integration is very much simple and comes with lot of flexibility which is the biggest advantage Spring comes with. Lest create a step wise project for simple application.

Project Structure

Create a Dynamic Web Project in your eclipse, lets say “Spring-Hibernate-Integration”. Add the required jar files for Spring and Hibernate and add the runtime environment, in this case we are adding Apache Tomcat 7. At the end our project structure and the required dependencies in the lib folder will be as shown below.

spring-hibernate-project-structure
spring-hibernate-project-structure

The libraries to be added –

spring-hibernate-jars
spring-hibernate-jars

Configuration (XML and Properties)

  1. WEB.XML file – It contains simple mapping of dispatcher servlet along with the welcome page to load.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Spring-Hibernate-Integration</display-name>
	
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>jsp/welcome.jsp</welcome-file>
	</welcome-file-list>
</web-app>

2. dispatcher-servlet.xml – It contains the details of Spring and hibernate beans to be used along with the configurations.

<?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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:annotation-config />

	<context:property-placeholder location="classpath:jdbc.properties" />

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

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

	<!-- JSP View resolver  -->
	<bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- Bean for Database driver and details -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${database.driver}" />
		<property name="url" value="${database.url}" />
		<property name="username" value="${database.user}" />
		<property name="password" value="${database.password}" />
	</bean>
	
	<!-- Session Factory for using data source -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
		</property>
		<!-- List of Beans that will be mapped to the Database table -->
		<property name="annotatedClasses">
			<list>
				<value>com.code2java.bean.User</value>
			</list>
		</property>
	</bean>

	<!-- Allowing Hibernate to maintain the Transactions on its own using Transaction Manager 
		 Transactions will be done using Session Factory created above for the DataSrurce 
	-->
	<bean id="hibernateTransactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
</beans>

In this configuration file, we have created a bean for data source, session factory and transaction manager. All these three beans will be used for all the transactions with the data base. Data source bean will give the details about the data base and will give the connection object. Session factory will create the session from the given data source so that transaction can be done using transaction manager with the data base. Transaction manager will make sure that all the transactions are safe and will take care of clearing and maintaining sessions in the server. While creating the session factory we have mentioned a bean that will be mapped to the data base table “users”. Please note, you can also configure such annotated beans apart from this xml file that is in your java files.

3. jdbc.properties file : This file contains the details of database like, driver, port, username, password, url etc. This file will be loaded in the dispatcher servlet to read the details and create a datasource.

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/code2java
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true

View Pages:

Lets create a JSP page which contains a form that will submit the data to the server to be stored in data base. Along with this, it will load all the user available in the database along with the current user submitted.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>code2java - Spring Hibernate Integration</title>
</head>
<body>
	<form method="post" action="addUser.do" modelAttribute="user">
		<table>
			<tr>
				<td><label>Name</label></td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<td><label>UserName</label></td>
				<td><input type="text" name="userName"></td>
			</tr>
			<tr>
				<td><label>Email</label></td>
				<td><input type="text" name="email"></td>
			</tr>
			<tr>
				<td><label>Password</label></td>
				<td><input type="password" name="password"></td>
			</tr>
			<tr>
				<td colspan="2"><input type="Submit" value="Submit"></td>
			</tr>
		</table>
	</form>

	<br />
	<b>Users Available : </b>
	<table border="1px solid" style="border-collapse: collapse;">
		<tr>
			<th>User</th>
			<th>Email</th>
		</tr>
		<c:forEach var="list" items="${model}">
			<tr>
				<td>${list.name}</td>
				<td>${list.email}</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

Controllers, Services and Beans

Lets create a controller class for mapping the requests.

package com.code2java.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.code2java.bean.User;
import com.code2java.service.UserServiceImpl;


@Controller
public class MainController {
	
	@Autowired
	private UserServiceImpl userService;
	
	@RequestMapping("addUser")
	public ModelAndView addUser(@ModelAttribute("user") User user, BindingResult result, 
			HttpServletRequest request, HttpServletResponse response)
	{
		userService.addUser(user);
		List<User> model = userService.getUserList();
		return new ModelAndView("welcome","model", model);
	}

}

The controller class requires a UserService to process the request and a User model to process on. Lets create a user service and a user DAO which will process user bean that is be mapped to the data base table “users”.

User Service Interface and implementation:

package com.code2java.service;

import java.util.List;

import com.code2java.bean.User;

public interface IUserService {
	public void addUser(User user);

	public List<User> getUserList();
}

User Service Implementation :

package com.code2java.service;

import java.util.List;

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

import com.code2java.bean.User;
import com.code2java.dao.UserDAO;

@Service("userService")
public class UserServiceImpl implements IUserService {
	
	@Autowired
	private UserDAO userDao;

	@Override
	public void addUser(User user) {
		userDao.addUser(user);
	}

	@Override
	public List<User> getUserList() {
		return userDao.getUser();
	}

}

User bean that consists of the mapping of each row to a single property of this POJO class. @Entity and @Table(name = “users”) annotations are used in the below bean class to map the bean with the “users” table in the data base. Each column is mapped to one of the columns in the table using @Column annotation.

package com.code2java.bean;

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

@Entity
@Table(name = "users")
public class User {

	@Id
	@GeneratedValue
	@Column(name = "id")
	private int id;

	@Column(name = "userName")
	private String name;

	@Column(name = "password")
	private String password;

	@Column(name = "email")
	private String email;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

UserDAO class to process the transactions:

package com.code2java.dao;

import java.util.List;


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

import com.code2java.bean.User;

@Repository("userDao")
public class UserDAO {
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Transactional
	public void addUser(User user)
	{
		sessionFactory.getCurrentSession().save(user);
	}
	
	@Transactional
	public List<User> getUser() {
		@SuppressWarnings("unchecked")
		List<User> userlist = sessionFactory.getCurrentSession().createCriteria(User.class).list();
		return userlist;
	}
	
}

Output

And we are done with the coding part now. Just execute your application on the server and see the results. In this case the output will be-

First page :

spring-hibernate-page
spring-hibernate-page

Initial table details before any submission :

spring-hibernate-table
spring-hibernate-table

Data submission :

spring-hibernate-data
spring-hibernate-data

Data submission response:

spring-hibernate-data-insert
spring-hibernate-data-insert

Table content after the data submission :

spring-hibernate-inserted-data
spring-hibernate-inserted-data

Hope this helps you.

Regards,

Nikhil Naoghare.

Related Posts

  • Abstract Class In JAVA

    Hello Friends, This tutorial is for all the Java followers. One of the best feature that is widely used is the term ‘Abstract’. This term can be used as either class or a simple method. An abstract method is any method that is just declared but not instantiated. In other words one can just create…

  • Threads in Java.

    Hello Friends, This is the tutorial for the java developers. One of the most significance feature of core java is Threading. Threading deals with the processing of Threads in a single java program. Let us learn what actually are Threads. *What are Threads? Threads are independently running processes that are isolated from each other upto…

  • Collections In Java.

    Hello friends, Welcome to another tutorial for java followers. You all may have heard about Collections, it is one of the amazing feature in java. Collections are the object for the group of elements, these elements are nothing but the different data structures like as Array Lists, Linked Lists, Vectors, Hash tables,Hash List, Trees, Hash…

  • Maven Installation.

    Hello Friends, This is one of my tutorial for installation of Maven on windows. Maven is a software project management tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information. Maven is an open source community and is a…

  • Jira Plugin Deployment.

    Hello Friends, This is one of the most important tutorial for all the jira developers. You may have heard about the plugins in jira which is a simple Java Archive File with .jar extension. This JAR file contains the class files and auxiliary resources associated with the applications. In Jira we can use Eclipse IDE…

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.