This article demonstrates how to use(integrate) Spring and Hibernate together. We already know that Spring is a Frontend framework and Hibernate(ORM) is a Backend framework. With the help of these two frameworks, we can create a dynamic web application.

Steps to be followed,

Step 1: Create a dynamic web project

Step 2: Configure web.xml and spring-servlet.xml file

Step 3: Download the required jars and add it to lib folder

Step 4: Create jdbc.properties file and specify the database properties

Step 5: Create 4 packages, Controller, Entity, Service and DAO

Step 6: Create folder with name jsps

Step 7: Create a database with name ‘crud’ and create table with name ‘student’

Let’s design database first,

database structure

NOTE: I am using MySQL DB throughout this article, you can use any other DB

First, let’s create DB by executing this command,

create database crud;

Now, let’s get into the DB,

use crud;

Now, let’s create a table

create table student(

     id int not null primary key auto_increment,

     name varchar(50) not null,

     email varchar(50) not null,

     gender varchar(50) not null,

     hobbies varchar(50) not null,

     city varchar(50) not null,

     address varchar(50) not null

);

Next step is to create dynamic web project in Eclipse,

Open eclipse->File->New->Dynamic web project->Project name->Select web module version 2.5->Finish

project structure

web.xml

<?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"   xmlns:web="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_2_5.xsd" id="WebApp_ID" version="2.5">
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <display-name>Spring-Hibernate</display-name>
 <servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>spring</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

spring-servlet.xml

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

 <!-- Add support for component scanning -->
 <context:component-scan base-package="com.codingbybushan" />
 <context:property-placeholder location="classpath:jdbc.properties" /> 

 <!-- Add support for conversion, formatting and validation support -->
 <mvc:annotation-driven />

 <!-- Define Spring MVC view resolver -->
 <beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <beans:property name="prefix" value="/WEB-INF/jsps/" />
  <beans:property name="suffix" value=".jsp" />
 </beans:bean>

 <!-- Step 1: Define Database Datasource/connection pool -->
 <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <beans:property name="driverClassName" value="${jdbc.driverName}"/>
  <beans:property name="url" value="${jdbc.databaseurl}" />
  <beans:property name="username" value="${jdbc.username}" />
  <beans:property name="password" value="${jdbc.password}" />
 </beans:bean>

 <!-- Step 2: Setup Hibernate session factory -->
 <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <beans:property name="dataSource" ref="dataSource" />
 <beans:property name="packagesToScan" value="com.codingbybushan.entity"/>
 <beans:property name="hibernateProperties">
  <beans:props>
   <beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
  </beans:props>
 </beans:property>
 </beans:bean>

 <!-- Step 3: Setup Hibernate transaction manager -->
 <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <beans:property name="sessionFactory" ref="sessionFactory" />
 </beans:bean>

 <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
 <tx:annotation-driven transaction-manager="transactionManager" />

</beans:beans>

jdbc.properties

jdbc.driverName=com.mysql.jdbc.Driver
jdbc.databaseurl=jdbc:mysql://localhost/crud
jdbc.username=root
jdbc.password=root
jdbc.dialect=org.hibernate.dialect.MySQLDialect

Student.java

package com.codingbybushan.entity;

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

@Entity @Table(name = "student")
public class Student {

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;

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

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

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

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

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

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

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getEmail() {
return email;
}

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

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getHobbies() {
return hobbies;
}

public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}

StudentController.java

package com.codingbybushan.controller;

import java.util.List;

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.RequestParam;

import com.codingbybushan.entity.Student;
import com.codingbybushan.service.StudentService;

@Controller @RequestMapping(value = "/student")
public class StudentController {

@Autowired
 StudentService studentService;

 @RequestMapping("/showFormForAdd")
 public String showAddForm(Model model){
 model.addAttribute("student", new Student());
 return "student-form";
 }

 @RequestMapping("/saveProcess")
 public String saveStudentObj(@ModelAttribute("student") Student studentObj){
 studentService.saveStudentObj(studentObj);
 return "redirect:/student/list";
 }

 @RequestMapping("/list")
 public String listOfStudents(Model model){
 model.addAttribute("studentsList", studentService.getAllStudents());
 return "list-students";
 }

 @RequestMapping("/displayUpdateForm")
 public String showUpdateForm(@RequestParam("studentId") int theId, Model model){
 model.addAttribute("student", studentService.getStudentObj(theId));
 return "student-form";
 }

 @RequestMapping("/displayDeleteForm")
 public String deleteStudentObj(@RequestParam("studentId") int theId, Model model){
 studentService.removeStudentObj(theId);
 return "redirect:/student/list";
 }
}

StudentService.java

package com.codingbybushan.service;

import java.util.List;

import com.codingbybushan.entity.Student;

public interface StudentService {

public void saveStudentObj(Student studentObj);

public List<Student> getAllStudents();

public Student getStudentObj(int theId);

public void removeStudentObj(int theId);

}

StudentServiceImpl.java

package com.codingbybushan.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.codingbybushan.dao.StudentDAO;
import com.codingbybushan.entity.Student;

@Service
public class StudentServiceImpl implements StudentService{

@Autowired
 StudentDAO studentDAO;

 @Override @Transactional
 public void saveStudentObj(Student studentObj) {
 studentDAO.saveStudentObj(studentObj);
 }

@Override @Transactional
 public List<Student> getAllStudents() {
 return studentDAO.getAllStudents();
 }

@Override @Transactional
 public Student getStudentObj(int theId) {
 return studentDAO.getStudentObj(theId);
 }

@Override @Transactional
 public void removeStudentObj(int theId) {
 studentDAO.removeStudentObj(theId);
 }

}

StudentDAO.java

package com.codingbybushan.dao;

import java.util.List;

import com.codingbybushan.entity.Student;

public interface StudentDAO {

public void saveStudentObj(Student studentObj);

public List<Student> getAllStudents();

public Student getStudentObj(int theId);

public void removeStudentObj(int theId);

}

StudentDAOImpl.java

package com.codingbybushan.dao;

import java.util.List;

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

import com.codingbybushan.entity.Student;

@Repository
public class StudentDAOImpl implements StudentDAO{

@Autowired
 SessionFactory sessionFactory;

 @Override
 public void saveStudentObj(Student studentObj) {
 sessionFactory.getCurrentSession().saveOrUpdate(studentObj);
 }

@Override
 public List<Student> getAllStudents() {
 Session currentSession = sessionFactory.getCurrentSession();
 List<Student> theQuery = currentSession.createQuery("from Student").list();
 return theQuery;
 }

@Override
 public Student getStudentObj(int theId) {
 Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, theId);
 return studentObj;
 }

@Override
 public void removeStudentObj(int theId) {
 Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, theId);
 sessionFactory.getCurrentSession().delete(studentObj);
 }

}

list-students.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1 align = "center">List Students</h1>
<button onclick = "window.location.href = 'showFormForAdd'; return false;">Add Student</button>

<hr />

<center>
<table border = "1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>Hobbies</th>
<th>City</th>
<th>Address</th>
<th>Action</th>
</tr>
<c:forEach items="${studentsList}" var = "s">
 <c:url var="updateLink" value="/student/displayUpdateForm.html">
 <c:param name="studentId" value="${s.id}" />
 </c:url>

<c:url var="deleteLink" value="/student/displayDeleteForm.html">
 <c:param name="studentId" value="${s.id}" />
 </c:url>
<tr>
<td>${s.name}</td>
<td>${s.email}</td>
<td>${s.gender}</td>
<td>${s.hobbies}</td>
<td>${s.city}</td>
<td>${s.address}</td>
<td>
 <a href="${updateLink}">Update</a>
 |
 <a href="${deleteLink}" onclick="if(!(confirm('Are you sure want to delete this Student permanently?'))) return false">Delete</a></td>
</tr>
</c:forEach></table>
</center>
</body>
</html>

student-form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
<h1>Provide Student Information</h1>

<hr />

<form:form action = "saveProcess.html" modelAttribute="student">
<table>
 <form:hidden path="id"/>
 <form:hidden path="" value = "${student.hobbies}" id = "hobbies"/>
<tr>
<td><b>Full Name:</b></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><b>Email:</b></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><b>Gender:</b></td>
<td><form:radiobutton path="gender" value = "Male"/>Male&nbsp;&nbsp;<form:radiobutton path="gender" value = "Female"/>Female</td>
</tr>
<tr>
<td><b>Hobbies:</b></td>
<td>
 <form:checkbox path="hobbies" value = "Cricket"/>Cricket

 <form:checkbox path="hobbies" value = "Football"/>Football

 <form:checkbox path="hobbies" value = "Volleyball"/>Volleyball

 <form:checkbox path="hobbies" value = "Hockey"/>Hockey</td>
</tr>
<tr>
<td><b>City:</b></td>
<td>
 <form:select path="city">
 <form:option value="0">--Select--</form:option>
 <form:option value="Banglore">Banglore</form:option>
 <form:option value="Hubli">Hubli</form:option>
 <form:option value="Davangere">Davangere</form:option>
 <form:option value="Mysore">Mysore</form:option>
 <form:option value="Belgaum">Belgaum</form:option>
 <form:option value="Tumkur">Tumkur</form:option>
 <form:option value="Chitradurga">Chitradurga</form:option>
 </form:select></td>
</tr>
<tr>
<td><b>Address:</b></td>
<td><form:textarea path="address"/></td>
</tr>
<tr>
<td></td>
<td>
 <input type = "submit" value = "Save" />
 <input type = "reset" value = "Reset" /></td>
</tr>
</table>
</form:form>

<hr />

<a href = "list">Back to List</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" />
<script type="text/javascript">
$(document).ready(function() {
var hobbies = $("#hobbies").val().split(",");
var $checkboxes = $("input[type=checkbox]");
$checkboxes.each(function(idx, element){
    if(hobbies.indexOf(element.value) != -1){
        element.setAttribute("checked", "checked");
        $("#hobbies").val("");
}
else{
    element.removeAttribute("checked");
}
});
});
</script>
</body>
</html>

index.jsp

<% response.sendRedirect("student/list"); %>

Finally, run the project on server, Here are the screenshots

 

Watch The Demo Video Here

You can download the jars from here

Please share this article with your friends. if you are looking for the ‘war’ file, do mail me @ sc.bushan.05@gmail.com

Thanks & Regards,
Bushan Sirgur

Advertisements