Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring MVC and Hibernate Integration CRUD with Maven (Spring 4 + Hibernate 4 + Maven 3)

In this particular project we will see how to integrate Spring MVC 4 with Hibernate4 project with Maven and will perform crud operations using MySql Database. We will see what dependencies are required to setup Spring4 with Hibernate4 and how to configure SessionFactory and Spring configurations.


Objectives

1) How to integrate Spring 4 MVC with HIbernate 4 using Maven
2) What dependencies are required to integrate Hibernate 4 with Spring 4
3) How to setup SessionFactory with Hibernate 4
4) How to perform Create, Add, Edit and Delete operations on a Spring project with Hibernate.


How to integrate Spring 4 MVC with HIbernate 4 using Maven

Let us start our discussion with getting a simple web project from maven, if you are new to maven go to How to setup a web project with maven.
Assuming that we have a simple web project with maven with us and imported that in Eclipse IDE, now let us discuss how to setup the project, follow the steps mentioned in the rest part of the blow one by one:


Database setup

Let us first create a dummy database for our project, below is a mysql script please copy and execute it in your query editor.

-- Dumping database structure for springhibernate_db
CREATE DATABASE IF NOT EXISTS `springhibernate_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `springhibernate_db`;


-- Dumping structure for table springhibernate_db.employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

-- Dumping data for table springhibernate_db.employee: ~3 rows (approximately)
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` (`id`, `first_name`, `last_name`, `email`, `phone`) VALUES
(10, 'Virat', 'Kohli', '[email protected]', '89876787890'),
(11, 'Sachin', 'Tendulkar', '[email protected]', '89898989898'),
(12, 'Virendra', 'Sehwag', '[email protected]', '8976778789');


Maven dependencies required to setup Spring MVC 4 with Hibernate 4 : pom.xml

We are done with getting a simple Web project with maven and database setup let us add required dependencies to it.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.beingjavaguys.sphbn</groupId>
<artifactId>SpringHibernateAnnotations</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringHibernateAnnotations Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
<spring.version>4.0.5.RELEASE</spring.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<log4j.version>1.2.17</log4j.version>
<jdk.version>1.7</jdk.version>
<context.path>SpringHibernateAnnotations</context.path>
</properties>
<developers>

<developer>
<id>Nagesh Chauhan</id>
<email>[email protected]</email>
<organization>beingjavaguys.com</organization>
<organizationUrl>http://www.beingjavaguys.com</organizationUrl>
<roles>
<role>Java Developer</role>
</roles>
<timezone>+5:30</timezone>
</developer>
</developers>

<build>
<finalName>${pom.artifactId}</finalName>

<plugins>
<!-- Maven compiler plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>


</dependencies>
</project>


Now clean and install the project from maven console 'mvn clean install' and supply 'maven eclipse:eclipse -Dwtpversion=2.0' again and refresh the project in eclipse so that all required dependencies are downloaded and imported in eclipse 'Deployment Assemblies'.


\src\main\webapp\WEB-INF\web.xml

Let us now add 'DispatcherServlet' to our web.xml file to tell the container that all upcoming requests will be handled by Spring itself.

<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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"
version="2.5">

<display-name>Sample Spring Maven Project</display-name>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>


\src\main\webapp\WEB-INF\spring-config.xml

This is simple spring configuration file, we have added a datasource bean here which is getting values from a property file, secondly hibernate session factory is being configured and a view resolver is being added to render related jsp's.

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

<context:component-scan base-package="com.beingjavaguys.controller" />
<context:property-placeholder location="classpath:database.properties" />
<mvc:annotation-driven />

<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>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.beingjavaguys.domain.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>

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

<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>


<bean id="dataDaoImpl" class="com.beingjavaguys.dao.DataDaoImpl" />
<bean id="dataServiceImpl" class="com.beingjavaguys.services.DataServiceImpl" />

</beans>


\src\main\java\com\beingjavaguys\controller\DataController.java

Now let us add a controller to the project, we have added all required request-mappings to it to perform CRUD operations. The code is self explanatory.

package com.beingjavaguys.controller;

import java.util.List;

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

import com.beingjavaguys.domain.Employee;
import com.beingjavaguys.services.DataService;

@Controller
public class DataController {

@Autowired
DataService dataService;

@RequestMapping("form")
public ModelAndView getForm(@ModelAttribute Employee employee) {
return new ModelAndView("form");
}

@RequestMapping("register")
public ModelAndView registerUser(@ModelAttribute Employee employee) {
dataService.insertRow(employee);
return new ModelAndView("redirect:list");
}

@RequestMapping("list")
public ModelAndView getList() {
List employeeList = dataService.getList();
return new ModelAndView("list", "employeeList", employeeList);
}

@RequestMapping("delete")
public ModelAndView deleteUser(@RequestParam int id) {
dataService.deleteRow(id);
return new ModelAndView("redirect:list");
}

@RequestMapping("edit")
public ModelAndView editUser(@RequestParam int id,
@ModelAttribute Employee employee) {
Employee employeeObject = dataService.getRowById(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
}

@RequestMapping("update")
public ModelAndView updateUser(@ModelAttribute Employee employee) {
dataService.updateRow(employee);
return new ModelAndView("redirect:list");
}

}



\src\main\java\com\beingjavaguys\domain\Employee.java

Now we will add an 'Entity' class to the project, this class represents the table in database. We have added '@Entity' annotation to make hibernate recognize that this POJO is a entity in db. Variable names are automatically mapped to table columns id they are same. In case of any difference we have to annotate the fields with '@Column' annotations. @Id represents surrogate key for table.

package com.beingjavaguys.domain;

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

@Entity
public class Employee {

@Id
@GeneratedValue
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

private String email;
private String phone;

public int getId() {
return id;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

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

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}




\src\main\java\com\beingjavaguys\dao\DataDao.java



package com.beingjavaguys.dao;

import java.util.List;

import com.beingjavaguys.domain.Employee;

public interface DataDao {
public int insertRow(Employee employee);

public List getList();

public Employee getRowById(int id);

public int updateRow(Employee employee);

public int deleteRow(int id);

}




\src\main\java\com\beingjavaguys\dao\DataDaoImpl.java

All Hibernate related action goes here, operations related to 'Create, Insert, Update and Delete' are being performed in appropriate methods, we are getting session object from an autowired sessionfactory.



package com.beingjavaguys.dao;

import java.io.Serializable;
import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.beingjavaguys.domain.Employee;

public class DataDaoImpl implements DataDao {

@Autowired
SessionFactory sessionFactory;

@Override
@Transactional
public int insertRow(Employee employee) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
}

@Override
public List getList() {
Session session = sessionFactory.openSession();
@SuppressWarnings("unchecked")
List employeeList = session.createQuery("from Employee")
.list();
session.close();
return employeeList;
}

@Override
public Employee getRowById(int id) {
Session session = sessionFactory.openSession();
Employee employee = (Employee) session.load(Employee.class, id);
return employee;
}

@Override
public int updateRow(Employee employee) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(employee);
tx.commit();
Serializable id = session.getIdentifier(employee);
session.close();
return (Integer) id;
}

@Override
public int deleteRow(int id) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee employee = (Employee) session.load(Employee.class, id);
session.delete(employee);
tx.commit();
Serializable ids = session.getIdentifier(employee);
session.close();
return (Integer) ids;
}

}



\src\main\java\com\beingjavaguys\services\DataService.java



package com.beingjavaguys.services;

import java.util.List;

import com.beingjavaguys.domain.Employee;

public interface DataService {
public int insertRow(Employee employee);

public List getList();

public Employee getRowById(int id);

public int updateRow(Employee employee);

public int deleteRow(int id);

}




\src\main\java\com\beingjavaguys\services\DataServiceImpl.java

A service layer does nothing but it makes the code more flexible and reusable, using an Service layer in your projects makes it easy to test the data layer.

package com.beingjavaguys.services;

import java.util.List;

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

import com.beingjavaguys.dao.DataDao;
import com.beingjavaguys.domain.Employee;

public class DataServiceImpl implements DataService {

@Autowired
DataDao dataDao;

@Override
public int insertRow(Employee employee) {
return dataDao.insertRow(employee);
}

@Override
public List getList() {
return dataDao.getList();
}

@Override
public Employee getRowById(int id) {
return dataDao.getRowById(id);
}

@Override
public int updateRow(Employee employee) {
return dataDao.updateRow(employee);
}

@Override
public int deleteRow(int id) {
return dataDao.deleteRow(id);
}

}





\src\main\webapp\WEB-INF\pages\form.jsp

Here we have very first jsp file, this will render a user registration form. The data entered here will be persisted to the database table using Hibernate.



<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | Registration Form</title>
</head>
<body>
<center>

<div style="color: teal; font-size: 30px">Being Java Guys |
Registration Form</div>



<c:url var="userRegistration" value="saveUser.html" />
<form:form id="registerForm" modelAttribute="employee" method="post"
action="register">
<table width="400px" height="150px">
<tr>
<td><form:label path="firstName">First Name</form:label>
</td>
<td><form:input path="firstName" />
</td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label>
</td>
<td><form:input path="lastName" />
</td>
</tr>
<tr>
<td><form:label path="email">Email</form:label>
</td>
<td><form:input path="email" />
</td>
</tr>
<tr>
<td><form:label path="phone">Phone</form:label>
</td>
<td><form:input path="phone" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>


<a href="list">Click Here to see User List</a>
</center>
</body>
</html>



\src\main\webapp\WEB-INF\pages\list.jsp

This view will show up a list of all employees stored in Database, we have associated 'Edit' and 'Delete' functionality to them so that records can be edited and deleted on the fly.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | User Details</title>
</head>
<body>
<center>

<div style="color: teal; font-size: 30px">Being Java Guys | User
Details</div>

<c:if test="${!empty employeeList}">
<table border="1" bgcolor="black" width="600px">
<tr
style="background-color: teal; color: white; text-align: center;"
height="40px">

<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<c:forEach items="${employeeList}" var="user">
<tr
style="background-color: white; color: black; text-align: center;"
height="30px">

<td><c:out value="${user.firstName}" />
</td>
<td><c:out value="${user.lastName}" />
</td>
<td><c:out value="${user.email}" />
</td>
<td><c:out value="${user.phone}" />
</td>
<td><a href="edit?id=${user.id}">Edit</a></td>
<td><a href="delete?id=${user.id}">Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>


<a href="form">Click Here to add new User</a>
</center>
</body>
</html>





\src\main\webapp\WEB-INF\pages\form.jsp

This view will render a edit form with auto fill values of employee table, once submitted all required updates will be reflected to db.


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | Edit User Details</title>
</head>
<body>
<center>

<div style="color: teal; font-size: 30px">Being Java Guys |
Edit Details</div>



<c:url var="userRegistration" value="saveUser.html" />
<form:form id="registerForm" modelAttribute="employee" method="post"
action="update">
<table width="400px" height="150px">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName" value="${employeeObject.firstName}" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" value="${employeeObject.lastName}"/></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" value="${employeeObject.email}"/></td>
</tr>
<tr>
<td><form:label path="phone">Phone</form:label></td>
<td><form:input path="phone" value="${employeeObject.phone}"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" />
</td>
</tr>
</table>
</form:form>



</center>
</body>
</html>




\src\main\webapp\index.jsp

At the end, we have redirected the default flow from 'index.jsp' to our registration form so that 'form' will open on the start up of project.

<%response.sendRedirect("form");%>
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>




Now we are all done, now if everything goes right and you have configured things correctly, we will see following screens on the browser.





That’s all about "Spring MVC and Hibernate Integration CRUD with Maven" In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.








Thanks for reading !
Being Java Guys Team

Download "Spring4 + Hibernate4 + Maven3 Integration Example Project" from "SkyDrive"





This post first appeared on Java, Struts 2, Spring, Hibernate, Solr, Mahout An, please read the originial post: here

Share the post

Spring MVC and Hibernate Integration CRUD with Maven (Spring 4 + Hibernate 4 + Maven 3)

×

Subscribe to Java, Struts 2, Spring, Hibernate, Solr, Mahout An

Get updates delivered right to your inbox!

Thank you for your subscription

×