Spring MVC with Hibernate CRUD example

In this article, We will learn about how to integrate Hibernate with Spring MVC application

Step 1

Create Spring MVC project, Please refer Spring MVC setup in eclipse article on how to do it.

Project structure


springmvc_hibernate_crud_proj_structure

Step 2

Update pom.xml with required dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>SpringMVCHibernateCRUD</groupId>
  5.     <artifactId>SpringMVCHibernateCRUD</artifactId>
  6.     <packaging>war</packaging>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <name>SpringMVCHibernateCRUD Maven Webapp</name>
  9.     <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.     <dependencies>
  14.         <dependency>
  15.             <groupId>junit</groupId>
  16.             <artifactId>junit</artifactId>
  17.             <version>3.8.1</version>
  18.             <scope>test</scope>
  19.         </dependency>
  20.        
  21.         <dependency>
  22.             <groupId>org.springframework</groupId>
  23.             <artifactId>spring-webmvc</artifactId>
  24.             <version>${org.springframework.version}</version>
  25.         </dependency>
  26.         <dependency>
  27.             <groupId>org.hibernate</groupId>
  28.             <artifactId>hibernate-core</artifactId>
  29.             <version>5.2.6.Final</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>mysql</groupId>
  33.             <artifactId>mysql-connector-java</artifactId>
  34.             <version>6.0.5</version>
  35.         </dependency>
  36.         <dependency>
  37.             <groupId>org.springframework</groupId>
  38.             <artifactId>spring-tx</artifactId>
  39.             <version>${org.springframework.version}</version>
  40.         </dependency>
  41.        
  42.         <dependency>
  43.             <groupId>org.springframework</groupId>
  44.             <artifactId>spring-orm</artifactId>
  45.             <version>${org.springframework.version}</version>
  46.         </dependency>
  47.        
  48.         <dependency>
  49.             <groupId>javax.servlet</groupId>
  50.             <artifactId>servlet-api</artifactId>
  51.             <version>2.5</version>
  52.         </dependency>
  53.         <dependency>
  54.             <groupId>javax.servlet.jsp</groupId>
  55.             <artifactId>jsp-api</artifactId>
  56.             <version>2.1</version>
  57.         </dependency>
  58.         <dependency>
  59.             <groupId>javax.servlet</groupId>
  60.             <artifactId>jstl</artifactId>
  61.             <version>1.2</version>
  62.         </dependency>
  63.     </dependencies>
  64.     <build>
  65.         <finalName>SpringMVCHibernateCRUD</finalName>
  66.     </build>
  67. </project>
<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>SpringMVCHibernateCRUD</groupId>
	<artifactId>SpringMVCHibernateCRUD</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCHibernateCRUD Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCHibernateCRUD</finalName>
	</build>
</project>

Step 3

Update web.xml file with Dispatcher servlet

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.   <display-name>Archetype Created Web Application</display-name>
  5.   <!-- Spring MVC dispatcher servlet -->
  6.     <servlet>
  7.         <servlet-name>mvc-dispatcher</servlet-name>
  8.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  9.         <init-param>
  10.             <param-name>contextConfigLocation</param-name>
  11.             <param-value>
  12.             /WEB-INF/spring-mvc.xml
  13.             </param-value>
  14.         </init-param>
  15.         <load-on-startup>1</load-on-startup>
  16.     </servlet>
  17.     <servlet-mapping>
  18.         <servlet-name>mvc-dispatcher</servlet-name>
  19.         <url-pattern>/</url-pattern>
  20.     </servlet-mapping>
  21.  
  22.     <listener>
  23.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  24.     </listener>
  25.     <context-param>
  26.         <param-name>contextConfigLocation</param-name>
  27.         <param-value>
  28.             /WEB-INF/spring-mvc.xml
  29.         </param-value>
  30.     </context-param>
  31. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring MVC dispatcher servlet -->
    <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-mvc.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>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-mvc.xml
        </param-value>
    </context-param>
</web-app>


we have defined a dispatcher servlet in web.xml and mapped it by the URL pattern “/”

Step 4

Create the Employee class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Employee")
  12. public class Employee {
  13.     @Id
  14.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  15.     @Column(name = "Employee_Id")
  16.     private Integer employeeId;
  17.    
  18.     @Column(name = "FirstName")
  19.     private String firstName;
  20.    
  21.     @Column(name = "LastName")
  22.     private String lastName;
  23.    
  24.     @Column(name = "Age")
  25.     private Integer age;
  26.    
  27.     @Column(name = "Education")
  28.     private String education;
  29.    
  30.     @Column(name = "Salary")
  31.     private Double salary;
  32.    
  33.     public Integer getEmployeeId() {
  34.         return employeeId;
  35.     }
  36.     public void setEmployeeId(Integer employeeId) {
  37.         this.employeeId = employeeId;
  38.     }
  39.     public String getFirstName() {
  40.         return firstName;
  41.     }
  42.     public void setFirstName(String firstName) {
  43.         this.firstName = firstName;
  44.     }
  45.     public String getLastName() {
  46.         return lastName;
  47.     }
  48.     public void setLastName(String lastName) {
  49.         this.lastName = lastName;
  50.     }
  51.     public Integer getAge() {
  52.         return age;
  53.     }
  54.     public void setAge(Integer age) {
  55.         this.age = age;
  56.     }
  57.     public String getEducation() {
  58.         return education;
  59.     }
  60.     public void setEducation(String education) {
  61.         this.education = education;
  62.     }
  63.     public Double getSalary() {
  64.         return salary;
  65.     }
  66.     public void setSalary(Double salary) {
  67.         this.salary = salary;
  68.     }
  69. }
package com.kb.model;

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="Employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private Integer employeeId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private Integer age;
	
	@Column(name = "Education")
	private String education;
	
	@Column(name = "Salary")
	private Double salary;
	
	public Integer getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
}

Step 5

Create the controller class

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10.  
  11. import com.kb.model.Employee;
  12. import com.kb.service.EmployeeService;
  13.  
  14. @Controller
  15. public class EmployeeController {
  16.    
  17.     @Autowired
  18.     private EmployeeService employeeService;
  19.  
  20.     @RequestMapping(value = "/employees", method = RequestMethod.GET)
  21.     public String listemployees(Model model) {
  22.         model.addAttribute("employee", new Employee());
  23.         model.addAttribute("employeeList", employeeService.listEmployees());
  24.         return "employee";
  25.     }
  26.  
  27.     // Same method For both Add and Update Employee
  28.     @RequestMapping(value = "/employee/add", method = RequestMethod.POST)
  29.     public String addemployee(@ModelAttribute("employee") Employee employee) {
  30.  
  31.         if (employee.getEmployeeId()==null || employee.getEmployeeId() == 0) {
  32.             // new employee, add it
  33.             employeeService.addEmployee(employee);
  34.         } else {
  35.             // existing employee, call update
  36.             employeeService.updateEmployee(employee);
  37.         }
  38.  
  39.         return "redirect:/employees";
  40.  
  41.     }
  42.  
  43.     @RequestMapping("/employee/remove/{id}")
  44.     public String removeemployee(@PathVariable("id") int id) {
  45.  
  46.         employeeService.removeEmployee(id);
  47.         return "redirect:/employees";
  48.     }
  49.  
  50.     @RequestMapping("/employee/edit/{id}")
  51.     public String editemployee(@PathVariable("id") int id, Model model) {
  52.         model.addAttribute("employee", employeeService.getEmployeeById(id));
  53.         model.addAttribute("employeeList", employeeService.listEmployees());
  54.         return "employee";
  55.     }
  56. }
package com.kb.controllers;

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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.model.Employee;
import com.kb.service.EmployeeService;

@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;

	@RequestMapping(value = "/employees", method = RequestMethod.GET)
	public String listemployees(Model model) {
		model.addAttribute("employee", new Employee());
		model.addAttribute("employeeList", employeeService.listEmployees());
		return "employee";
	}

	// Same method For both Add and Update Employee
	@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
	public String addemployee(@ModelAttribute("employee") Employee employee) {

		if (employee.getEmployeeId()==null || employee.getEmployeeId() == 0) {
			// new employee, add it
			employeeService.addEmployee(employee);
		} else {
			// existing employee, call update
			employeeService.updateEmployee(employee);
		}

		return "redirect:/employees";

	}

	@RequestMapping("/employee/remove/{id}")
	public String removeemployee(@PathVariable("id") int id) {

		employeeService.removeEmployee(id);
		return "redirect:/employees";
	}

	@RequestMapping("/employee/edit/{id}")
	public String editemployee(@PathVariable("id") int id, Model model) {
		model.addAttribute("employee", employeeService.getEmployeeById(id));
		model.addAttribute("employeeList", employeeService.listEmployees());
		return "employee";
	}
}

Step 6

Create the EmployeeService interface

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.Employee;
  6.  
  7. public interface EmployeeService {
  8.    
  9.     public void addEmployee(Employee employee);
  10.    
  11.     public void updateEmployee(Employee employee);
  12.    
  13.     public Employee getEmployeeById(int id);
  14.    
  15.     public void removeEmployee(int id);
  16.    
  17.     public List<Employee> listEmployees();
  18.  
  19.  
  20. }
package com.kb.service;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeService {
	
	public void addEmployee(Employee employee);
	
	public void updateEmployee(Employee employee);
	
	public Employee getEmployeeById(int id);
	
	public void removeEmployee(int id);
	
	public List<Employee> listEmployees();


}

Step 7

Create the EmployeeServiceImpl class

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import com.kb.dao.EmployeeDAO;
  9.  
  10. import com.kb.model.Employee;
  11.  
  12. @Service
  13. public class EmployeeServiceImpl implements EmployeeService {
  14.    
  15.     @Autowired
  16.     private EmployeeDAO employeeDAO;
  17.  
  18.     public void setemployeeDAO(EmployeeDAO employeeDAO) {
  19.         this.employeeDAO = employeeDAO;
  20.     }
  21.  
  22.     @Override
  23.     @Transactional
  24.     public void addEmployee(Employee employee) {
  25.         employeeDAO.addEmployee(employee);
  26.     }
  27.  
  28.     @Override
  29.     @Transactional
  30.     public void updateEmployee(Employee employee) {
  31.         employeeDAO.updateEmployee(employee);
  32.     }
  33.  
  34.     @Override
  35.     @Transactional
  36.     public List<Employee> listEmployees() {
  37.         return this.employeeDAO.listEmployees();
  38.     }
  39.  
  40.     @Override
  41.     @Transactional
  42.     public Employee getEmployeeById(int id) {
  43.         return employeeDAO.getEmployeeById(id);
  44.     }
  45.  
  46.     @Override
  47.     @Transactional
  48.     public void removeEmployee(int id) {
  49.         employeeDAO.removeEmployee(id);
  50.     }
  51. }
package com.kb.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.kb.dao.EmployeeDAO;

import com.kb.model.Employee;

@Service
public class EmployeeServiceImpl implements EmployeeService {
	
	@Autowired
	private EmployeeDAO employeeDAO;

	public void setemployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	@Override
	@Transactional
	public void addEmployee(Employee employee) {
		employeeDAO.addEmployee(employee);
	}

	@Override
	@Transactional
	public void updateEmployee(Employee employee) {
		employeeDAO.updateEmployee(employee);
	}

	@Override
	@Transactional
	public List<Employee> listEmployees() {
		return this.employeeDAO.listEmployees();
	}

	@Override
	@Transactional
	public Employee getEmployeeById(int id) {
		return employeeDAO.getEmployeeById(id);
	}

	@Override
	@Transactional
	public void removeEmployee(int id) {
		employeeDAO.removeEmployee(id);
	}
}

Step 8

Create the EmployeeDAO interface

  1. package com.kb.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.Employee;
  6.  
  7. public interface EmployeeDAO {
  8.    
  9.     public void addEmployee(Employee employee);
  10.    
  11.     public void updateEmployee(Employee employee);
  12.    
  13.     public Employee getEmployeeById(int id);
  14.    
  15.     public void removeEmployee(int id);
  16.    
  17.     public List<Employee> listEmployees();
  18.  
  19. }
package com.kb.dao;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeDAO {
	
	public void addEmployee(Employee employee);
	
	public void updateEmployee(Employee employee);
	
	public Employee getEmployeeById(int id);
	
	public void removeEmployee(int id);
	
	public List<Employee> listEmployees();

}

Step 9

Create the EmployeeDAOImpl class

  1. package com.kb.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Repository;
  9.  
  10. import com.kb.model.Employee;
  11.  
  12. @Repository
  13. public class EmployeeDAOImpl implements EmployeeDAO{
  14.    
  15.     @Autowired
  16.      private SessionFactory sessionFactory;
  17.    
  18.     @Override
  19.     public void addEmployee(Employee employee) {
  20.         Session session = sessionFactory.getCurrentSession();
  21.         session.persist(employee);
  22.     }
  23.  
  24.     @Override
  25.     public void updateEmployee(Employee employee) {
  26.         Session session = sessionFactory.getCurrentSession();
  27.         session.update(employee);
  28.     }
  29.  
  30.     @SuppressWarnings("unchecked")
  31.     @Override
  32.     public List<Employee> listEmployees() {
  33.         Session session = sessionFactory.getCurrentSession();
  34.         List<Employee> EmployeesList = session.createQuery("from Employee").list();
  35.         return EmployeesList;
  36.     }
  37.  
  38.     @Override
  39.     public Employee getEmployeeById(int id) {
  40.         Session session = sessionFactory.getCurrentSession();      
  41.         Employee employee = (Employee) session.get(Employee.class, new Integer(id));
  42.         return employee;
  43.     }
  44.  
  45.     @Override
  46.     public void removeEmployee(int id) {
  47.         Session session = sessionFactory.getCurrentSession();
  48.         Employee employee = (Employee) session.get(Employee.class, new Integer(id));
  49.         if(null != employee){
  50.             session.delete(employee);
  51.         }
  52.     }
  53. }
package com.kb.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.kb.model.Employee;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO{
	
	@Autowired
	 private SessionFactory sessionFactory;
	
	@Override
	public void addEmployee(Employee employee) {
		Session session = sessionFactory.getCurrentSession();
		session.persist(employee);
	}

	@Override
	public void updateEmployee(Employee employee) {
		Session session = sessionFactory.getCurrentSession();
		session.update(employee);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> listEmployees() {
		Session session = sessionFactory.getCurrentSession();
		List<Employee> EmployeesList = session.createQuery("from Employee").list();
		return EmployeesList;
	}

	@Override
	public Employee getEmployeeById(int id) {
		Session session = sessionFactory.getCurrentSession();		
		Employee employee = (Employee) session.get(Employee.class, new Integer(id));
		return employee;
	}

	@Override
	public void removeEmployee(int id) {
		Session session = sessionFactory.getCurrentSession();
		Employee employee = (Employee) session.get(Employee.class, new Integer(id));
		if(null != employee){
			session.delete(employee);
		}
	}
}

Step 10

Create the Spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xmlns:tx="http://www.springframework.org/schema/tx"
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  8.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  9.        http://www.springframework.org/schema/context
  10.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  11.        http://www.springframework.org/schema/mvc
  12.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  13.        http://www.springframework.org/schema/tx
  14.        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  15.  
  16.     <context:component-scan base-package="com.kb" />
  17.     <mvc:annotation-driven />
  18.     <context:property-placeholder location="classpath:database.properties"/>
  19.  
  20.         <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
  21.  
  22.         <bean id="viewResolver"
  23.             class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  24.             <property name="prefix" value="/WEB-INF/pages/" />
  25.             <property name="suffix" value=".jsp" />
  26.         </bean>
  27.  
  28.         <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  29.             id="dataSource">
  30.             <property name="driverClassName" value="${database.driver}"></property>
  31.             <property name="url" value="${database.url}"></property>
  32.             <property name="username" value="${database.user}"></property>
  33.             <property name="password" value="${database.password}"></property>
  34.         </bean>
  35.  
  36.         <bean
  37.             class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
  38.             id="sessionFactory">
  39.             <property name="dataSource" ref="dataSource"></property>
  40.             <property name="annotatedClasses">
  41.                 <list>
  42.                     <value>com.kb.model.Employee</value>
  43.                 </list>
  44.             </property>
  45.             <property name="hibernateProperties">
  46.                 <props>
  47.                     <prop key="hibernate.dialect">${hibernate.dialect}</prop>
  48.                     <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
  49.                     <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
  50.                 </props>
  51.             </property>
  52.         </bean>
  53.  
  54.         <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager"
  55.             id="hibernateTransactionManager">
  56.             <property name="sessionFactory" ref="sessionFactory"></property>
  57.         </bean>
  58.        
  59.         <bean id="messageSource"
  60.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  61.         <property name="basename" value="classpath:messages" />
  62.         <property name="defaultEncoding" value="UTF-8" />
  63.     </bean>
  64.    
  65.     <bean id="localeResolver"
  66.         class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  67.         <property name="defaultLocale" value="en" />
  68.     </bean>
  69.  
  70.     <mvc:interceptors>
  71.         <bean id="localeChangeInterceptor"
  72.             class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  73.             <property name="paramName" value="language" />
  74.         </bean>
  75.     </mvc:interceptors>
  76.  
  77. </beans>
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

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

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

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

		<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
			id="dataSource">
			<property name="driverClassName" value="${database.driver}"></property>
			<property name="url" value="${database.url}"></property>
			<property name="username" value="${database.user}"></property>
			<property name="password" value="${database.password}"></property>
		</bean>

		<bean
			class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
			id="sessionFactory">
			<property name="dataSource" ref="dataSource"></property>
			<property name="annotatedClasses">
				<list>
					<value>com.kb.model.Employee</value>
				</list>
			</property>
			<property name="hibernateProperties">
				<props>
					<prop key="hibernate.dialect">${hibernate.dialect}</prop>
					<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
					<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
				</props>
			</property>
		</bean>

		<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager"
			id="hibernateTransactionManager">
			<property name="sessionFactory" ref="sessionFactory"></property>
		</bean>
		
		<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>
 
    <mvc:interceptors>
        <bean id="localeChangeInterceptor"
            class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="language" />
        </bean>
    </mvc:interceptors>

</beans>

Step 11

Create database.properties

database.driver=com.mysql.jdbc.Driver

database.url=jdbc:mysql://localhost:3306/javainsimpleway

database.user=root

database.password=root

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.hbm2ddl.auto=update

Step 12

Create messages_en.properties

AddEmployee=Add New Employee

EmployeeID=Employee Id

FirstName=First Name

LastName=Last Name

Age=Age

Education=Education

Salary=Salary

Submit=Submit

employeeList=Employee List

EditEmployee=Edit Employee

Step 13

Create the employee.jsp page for CRUD operations

  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  2. <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
  3. <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
  4. <%@ page session="false" %>
  5. <html>
  6. <head>
  7.     <title>Employee Page</title>
  8.     <style type="text/css">
  9.         .empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
  10.         .empTable td{font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;border-
  11.                               style:solid;border-width:2px;overflow:hidden;word-break:normal;border-
  12.                               color:#ccc;color:#00FF00;background-color:#FF0000;}
  13.         .empTable th{font-family:Arial, sans-serif;font-size:16px;font-weight:normal;padding:10px
  14.                               5px;border-style:solid;border-width:2px;overflow:hidden;word-break:normal;border-
  15.                               color:#ccc;color:#000000;background-color:#FF4500;}
  16.         .empTable .empTable-4eph{background-color:#C0C0C0}
  17.     </style>
  18. </head>
  19. <body>
  20.  
  21.     <c:if test="${empty employee.employeeId}">
  22.     <h1>
  23.     <spring:message code="AddEmployee"/>
  24.     </h1>
  25.     </c:if>
  26.  
  27.  
  28. <c:url var="addAction" value="/employee/add" ></c:url>
  29.  
  30. <form:form action="${addAction}" modelAttribute="employee">
  31. <table>
  32.     <c:if test="${not empty employee.employeeId}">
  33.     <h1><spring:message code="EditEmployee"/></h1>
  34.     <tr>
  35.         <td>
  36.             <form:label path="employeeId">
  37.                 <spring:message code="EmployeeID"/>
  38.             </form:label>
  39.         </td>
  40.         <td>
  41.             <form:input path="employeeId" readonly="true" size="8"  disabled="true" />
  42.             <form:hidden path="employeeId" />
  43.         </td>
  44.     </tr>
  45.     </c:if>
  46.  
  47.     <tr>
  48.         <td>
  49.             <form:label path="firstName">
  50.                 <spring:message code="FirstName"/>
  51.             </form:label>
  52.         </td>
  53.         <td>
  54.             <form:input path="firstName" />
  55.         </td>
  56.     </tr>
  57.  
  58.     <tr>
  59.         <td>
  60.             <form:label path="lastName">
  61.                 <spring:message code="LastName"/>
  62.             </form:label>
  63.         </td>
  64.         <td>
  65.             <form:input path="lastName" />
  66.         </td>
  67.     </tr>
  68.  
  69.     <tr>
  70.         <td>
  71.             <form:label path="age">
  72.                 <spring:message code="Age"/>
  73.             </form:label>
  74.         </td>
  75.         <td>
  76.             <form:input path="age" />
  77.         </td>
  78.     </tr>
  79.  
  80.     <tr>
  81.         <td>
  82.             <form:label path="education">
  83.                 <spring:message code="Education"/>
  84.             </form:label>
  85.         </td>
  86.         <td>
  87.             <form:input path="education" />
  88.         </td>
  89.     </tr>
  90.  
  91.     <tr>
  92.         <td>
  93.             <form:label path="salary">
  94.                 <spring:message code="Salary"/>
  95.             </form:label>
  96.         </td>
  97.         <td>
  98.             <form:input path="salary" />
  99.         </td>
  100.     </tr>
  101.  
  102.     <tr>
  103.         <td colspan="2">
  104.                 <input type="submit"
  105.                     value="<spring:message code="Submit"/>" />
  106.         </td>
  107.     </tr>
  108.  
  109. </table>   
  110. </form:form>
  111. <br>
  112.  
  113. <c:if test="${not empty employeeList}">
  114. <h3><spring:message code="employeeList"/></h3>
  115.     <table class="empTable">
  116.     <tr>
  117.         <th width="80">ID</th>
  118.         <th width="120">First Name</th>
  119.         <th width="120">Last Name</th>
  120.         <th width="120">Age</th>
  121.         <th width="120">Education</th>
  122.         <th width="120">Salary</th>
  123.         <th width="60">Edit</th>
  124.         <th width="60">Delete</th>
  125.     </tr>
  126.  
  127.     <c:forEach items="${employeeList}" var="employee">
  128.         <tr>
  129.             <td>${employee.employeeId}</td>
  130.             <td>${employee.firstName}</td>
  131.             <td>${employee.lastName}</td>
  132.             <td>${employee.age}</td>
  133.             <td>${employee.education}</td>
  134.             <td>${employee.salary}</td>
  135.             <td><a href="<c:url value='/employee/edit/${employee.employeeId}' />" >Edit</a></td>
  136.             <td><a href="<c:url value='employee/remove/${employee.employeeId}' />" >Delete</a></td>
  137.         </tr>
  138.     </c:forEach>
  139.     </table>
  140. </c:if>
  141. </body>
  142. </html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
	<title>Employee Page</title>
	<style type="text/css">
		.empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
		.empTable td{font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;border-
                              style:solid;border-width:2px;overflow:hidden;word-break:normal;border- 
                              color:#ccc;color:#00FF00;background-color:#FF0000;}
		.empTable th{font-family:Arial, sans-serif;font-size:16px;font-weight:normal;padding:10px 
                              5px;border-style:solid;border-width:2px;overflow:hidden;word-break:normal;border-
                              color:#ccc;color:#000000;background-color:#FF4500;}
		.empTable .empTable-4eph{background-color:#C0C0C0}
	</style>
</head>
<body>

	<c:if test="${empty employee.employeeId}">
	<h1>
	<spring:message code="AddEmployee"/>
	</h1>
	</c:if>


<c:url var="addAction" value="/employee/add" ></c:url>

<form:form action="${addAction}" modelAttribute="employee">
<table>
	<c:if test="${not empty employee.employeeId}">
	<h1><spring:message code="EditEmployee"/></h1>
	<tr>
		<td>
			<form:label path="employeeId">
				<spring:message code="EmployeeID"/>
			</form:label>
		</td>
		<td>
			<form:input path="employeeId" readonly="true" size="8"  disabled="true" />
			<form:hidden path="employeeId" />
		</td> 
	</tr>
	</c:if>

	<tr>
		<td>
			<form:label path="firstName">
				<spring:message code="FirstName"/>
			</form:label>
		</td>
		<td>
			<form:input path="firstName" />
		</td> 
	</tr>

	<tr>
		<td>
			<form:label path="lastName">
				<spring:message code="LastName"/>
			</form:label>
		</td>
		<td>
			<form:input path="lastName" />
		</td> 
	</tr>

	<tr>
		<td>
			<form:label path="age">
				<spring:message code="Age"/>
			</form:label>
		</td>
		<td>
			<form:input path="age" />
		</td>
	</tr>

	<tr>
		<td>
			<form:label path="education">
				<spring:message code="Education"/>
			</form:label>
		</td>
		<td>
			<form:input path="education" />
		</td>
	</tr>

	<tr>
		<td>
			<form:label path="salary">
				<spring:message code="Salary"/>
			</form:label>
		</td>
		<td>
			<form:input path="salary" />
		</td>
	</tr>

	<tr>
		<td colspan="2">
				<input type="submit"
					value="<spring:message code="Submit"/>" />
		</td>
	</tr>

</table>	
</form:form>
<br>

<c:if test="${not empty employeeList}">
<h3><spring:message code="employeeList"/></h3>
	<table class="empTable">
	<tr>
		<th width="80">ID</th>
		<th width="120">First Name</th>
		<th width="120">Last Name</th>
		<th width="120">Age</th>
		<th width="120">Education</th>
		<th width="120">Salary</th>
		<th width="60">Edit</th>
		<th width="60">Delete</th>
	</tr>

	<c:forEach items="${employeeList}" var="employee">
		<tr>
			<td>${employee.employeeId}</td>
			<td>${employee.firstName}</td>
			<td>${employee.lastName}</td>
			<td>${employee.age}</td>
			<td>${employee.education}</td>
			<td>${employee.salary}</td>
			<td><a href="<c:url value='/employee/edit/${employee.employeeId}' />" >Edit</a></td>
			<td><a href="<c:url value='employee/remove/${employee.employeeId}' />" >Delete</a></td>
		</tr>
	</c:forEach>
	</table>
</c:if>
</body>
</html>

Step 14

Build and deploy the project

Step 15

Let’s see the output of all CRUD operations

Access below url

http://localhost:8080/SpringMVCHibernateCRUD/employees

springmvc_hibernate_crud_output1

Since we don’t have any employees in the database, we get a form to add new employee details

Step 16

Fill the employee details and Submit


springmvc_hibernate_crud_fill_emp_data_output2

Add 2 more employees in the same way and check the below output

springmvc_hibernate_crud_fill_emp_data_output3

Update the employee by editing the details

Click on edit on employee row whose id is ‘3’, below form will open with prepopulated data

Updating the age to 35

springmvc_hibernate_crud_edit_emp_data_output4

After submission, we can see the updated age in the result list

springmvc_hibernate_crud_edit_emp_data_output5

Delete the employee

Click on delete on any one of the employee and check the result

springmvc_hibernate_crud_delete_emp_data_output6a

After deletion, we can see that i have deleted one employee whose id is ‘3’

springmvc_hibernate_crud_delete_emp_data_output6

Download this project SpringMVCHibernateCRUD.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on