Tuesday 14 June 2016

Spring 3.0 MVC with Hibernate 3.0 CRUD Example

Spring 3.0 MVC with Hibernate 3.0 CRUD Example

In this example show how to write a simple web based application with CRUD  operation using Spring3 MVC Framwork with Hibernate3 using Annotation, which can handle CRUD inside its controllers. To start with it, let us have working STS IDE in place and follow the following steps to develop a Dynamic Form based Web Application using Spring Web Framework:

Step 1Create a Database DAVDB on MySql Database and also we create Employee table on this database.
  1. CREATE TABLE Employee(
  2.    EMPID   INT NOT NULL AUTO_INCREMENT,
  3.    EMPNAME VARCHAR(20) NOT NULL,
  4.    EMPAGE  INT NOT NULL,
  5.    SALARY BIGINT NOT NULL,
  6.    ADDRESS VARCHAR(20) NOT NULL
  7.    PRIMARY KEY (ID)
  8. );

Step 2Create a database.properties for database configuration information in the resources folder under src folder in the created project.
  1. database.driver=com.mysql.jdbc.Driver
  2. database.url=jdbc:mysql://localhost:3306/DAVDB
  3. database.user=root
  4. database.password=root
  5. hibernate.dialect=org.hibernate.dialect.MySQLDialect
  6. hibernate.show_sql=true
  7. hibernate.hbm2ddl.auto=update

Step 3: Create a Dynamic Web Project with a name Spring3HibernateApp and create packagescom.dineshonjava.controllercom.dineshonjava.beancom.dineshonjava.daocom.dineshonjava.service, com.dineshonjava.model under the src folder in the created project.

Step 4: Add below mentioned Spring 3.0 and Hibernate 3.0 related libraries and other libraries into the folder WebRoot/WEB-INF/lib
Step 5: Create a Java class EmployeeController, EmployeeBean, Employee, EmployeeDao, EmployeeDaoImpl, EmployeeService, EmployeeServiceImpl under the respective packages..

Step 6: Create Spring configuration files web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/ and WebRoot/WEB-INF/config folders.

Step 7: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file addEmployee.jsp, employeesList.jsp and index.jsp under this sub-folder.

Step 8: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder /WebRoot/WEB-INF/config and export the application as explained below.

APPLICATION ARCHITECTURE

We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called EmployeeService.

EmployeeBean.java
  1. package com.dineshonjava.bean;
  2. /**
  3.  * @author Dinesh Rajput
  4.  *
  5.  */
  6. public class EmployeeBean {
  7.  private Integer id;
  8.  private String name;
  9.  private Integer age;
  10.  private Long salary;
  11.  private String address;
  12.  
  13.  public Long getSalary() {
  14.   return salary;
  15.  }
  16.  public void setSalary(Long salary) {
  17.   this.salary = salary;
  18.  }
  19.  public Integer getId() {
  20.   return id;
  21.  }
  22.  public void setId(Integer id) {
  23.   this.id = id;
  24.  }
  25.  public String getName() {
  26.   return name;
  27.  }
  28.  public void setName(String name) {
  29.   this.name = name;
  30.  }
  31.  public Integer getAge() {
  32.   return age;
  33.  }
  34.  public void setAge(Integer age) {
  35.   this.age = age;
  36.  }
  37.  public String getAddress() {
  38.   return address;
  39.  }
  40.  public void setAddress(String address) {
  41.   this.address = address;
  42.  }
  43. }
Employee.java
  1. package com.dineshonjava.model;
  2. import java.io.Serializable;
  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.  * @author Dinesh Rajput
  11.  *
  12.  */
  13. @Entity
  14. @Table(name="Employee")
  15. public class Employee implements Serializable{
  16.  private static final long serialVersionUID = -723583058586873479L;
  17.  
  18.  @Id
  19.  @GeneratedValue(strategy=GenerationType.AUTO)
  20.  @Column(name = "empid")
  21.  private Integer empId;
  22.  
  23.  @Column(name="empname")
  24.  private String empName;
  25.  
  26.  @Column(name="empaddress")
  27.  private String empAddress;
  28.  
  29.  @Column(name="salary")
  30.  private Long salary;
  31.  
  32.  @Column(name="empAge")
  33.  private Integer empAge;
  34.  public Integer getEmpId() {
  35.   return empId;
  36.  }
  37.  public void setEmpId(Integer empId) {
  38.   this.empId = empId;
  39.  }
  40.  public String getEmpName() {
  41.   return empName;
  42.  }
  43.  public void setEmpName(String empName) {
  44.   this.empName = empName;
  45.  }
  46.  public String getEmpAddress() {
  47.   return empAddress;
  48.  }
  49.  public void setEmpAddress(String empAddress) {
  50.   this.empAddress = empAddress;
  51.  }
  52.  public Long getSalary() {
  53.   return salary;
  54.  }
  55.  public void setSalary(Long salary) {
  56.   this.salary = salary;
  57.  }
  58.  public Integer getEmpAge() {
  59.   return empAge;
  60.  }
  61.  public void setEmpAge(Integer empAge) {
  62.   this.empAge = empAge;
  63.  }
  64. }
EmployeeDao.java
  1. package com.dineshonjava.dao;
  2. import java.util.List;
  3. import com.dineshonjava.model.Employee;
  4. /**
  5.  * @author Dinesh Rajput
  6.  *
  7.  */
  8. public interface EmployeeDao {
  9.  
  10.  public void addEmployee(Employee employee);
  11.  public List<Employee> listEmployeess();
  12.  
  13.  public Employee getEmployee(int empid);
  14.  
  15.  public void deleteEmployee(Employee employee);
  16. }
EmployeeDaoImpl.java
  1. package com.dineshonjava.dao;
  2. import java.util.List;
  3. import org.hibernate.SessionFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Repository;
  6. import com.dineshonjava.model.Employee;
  7. /**
  8.  * @author Dinesh Rajput
  9.  *
  10.  */
  11. @Repository("employeeDao")
  12. public class EmployeeDaoImpl implements EmployeeDao {
  13.  @Autowired
  14.  private SessionFactory sessionFactory;
  15.  
  16.  public void addEmployee(Employee employee) {
  17.    sessionFactory.getCurrentSession().saveOrUpdate(employee);
  18.  }
  19.  @SuppressWarnings("unchecked")
  20.  public List<Employee> listEmployeess() {
  21.   return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
  22.  }
  23.  public Employee getEmployee(int empid) {
  24.   return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
  25.  }
  26.  public void deleteEmployee(Employee employee) {
  27.   sessionFactory.getCurrentSession().createQuery("DELETE FROM Employee WHERE empid = "+employee.getEmpId()).executeUpdate();
  28.  }
  29. }
EmployeeService.java
  1. package com.dineshonjava.service;
  2. import java.util.List;
  3. import com.dineshonjava.model.Employee;
  4. /**
  5.  * @author Dinesh Rajput
  6.  *
  7.  */
  8. public interface EmployeeService {
  9.  
  10.  public void addEmployee(Employee employee);
  11.  public List<Employee> listEmployeess();
  12.  
  13.  public Employee getEmployee(int empid);
  14.  
  15.  public void deleteEmployee(Employee employee);
  16. }
EmployeeServiceImpl.java
  1. package com.dineshonjava.service;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import org.springframework.transaction.annotation.Propagation;
  6. import org.springframework.transaction.annotation.Transactional;
  7. import com.dineshonjava.dao.EmployeeDao;
  8. import com.dineshonjava.model.Employee;
  9. /**
  10.  * @author Dinesh Rajput
  11.  *
  12.  */
  13. @Service("employeeService")
  14. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
  15. public class EmployeeServiceImpl implements EmployeeService {
  16.  @Autowired
  17.  private EmployeeDao employeeDao;
  18.  
  19.  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
  20.  public void addEmployee(Employee employee) {
  21.   employeeDao.addEmployee(employee);
  22.  }
  23.  
  24.  public List<Employee> listEmployeess() {
  25.   return employeeDao.listEmployeess();
  26.  }
  27.  public Employee getEmployee(int empid) {
  28.   return employeeDao.getEmployee(empid);
  29.  }
  30.  
  31.  public void deleteEmployee(Employee employee) {
  32.   employeeDao.deleteEmployee(employee);
  33.  }
  34. }
EmployeeController.java
  1. package com.dineshonjava.controller;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.web.bind.annotation.ModelAttribute;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.servlet.ModelAndView;
  13. import com.dineshonjava.bean.EmployeeBean;
  14. import com.dineshonjava.model.Employee;
  15. import com.dineshonjava.service.EmployeeService;
  16. /**
  17.  * @author Dinesh Rajput
  18.  *
  19.  */
  20. @Controller
  21. public class EmployeeController {
  22.  
  23.  @Autowired
  24.  private EmployeeService employeeService;
  25.  
  26. @RequestMapping(value = "/save", method = RequestMethod.POST)
  27. public ModelAndView saveEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
  28.    BindingResult result) {
  29.   Employee employee = prepareModel(employeeBean);
  30.   employeeService.addEmployee(employee);
  31.   return new ModelAndView("redirect:/add.html");
  32.  }
  33.  @RequestMapping(value="/employees", method = RequestMethod.GET)
  34.  public ModelAndView listEmployees() {
  35.   Map<String Object> model = new HashMap<String Object>();
  36.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  37.   return new ModelAndView("employeesList", model);
  38.  }
  39.  @RequestMapping(value = "/add", method = RequestMethod.GET)
  40.  public ModelAndView addEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
  41.    BindingResult result) {
  42.   Map<String, Object> model = new HashMap<String, Object>();
  43.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  44.   return new ModelAndView("addEmployee", model);
  45.  }
  46.  
  47. @RequestMapping(value = "/index", method = RequestMethod.GET)
  48. public ModelAndView welcome() {
  49.   return new ModelAndView("index");
  50.  }
  51. @RequestMapping(value = "/delete", method = RequestMethod.GET)
  52. public ModelAndView editEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
  53.    BindingResult result) {
  54.   employeeService.deleteEmployee(prepareModel(employeeBean));
  55.   Map<String, Object> model = new HashMap<String, Object>();
  56.   model.put("employee", null);
  57.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  58.   return new ModelAndView("addEmployee", model);
  59.  }
  60.  
  61. @RequestMapping(value = "/edit", method = RequestMethod.GET)
  62. public ModelAndView deleteEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
  63.    BindingResult result) {
  64.   Map<String, Object> model = new HashMap<String, Object>();
  65.   model.put("employee", prepareEmployeeBean(employeeService.getEmployee(employeeBean.getId())));
  66.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  67.   return new ModelAndView("addEmployee", model);
  68.  }
  69.  
  70.  private Employee prepareModel(EmployeeBean employeeBean){
  71.   Employee employee = new Employee();
  72.   employee.setEmpAddress(employeeBean.getAddress());
  73.   employee.setEmpAge(employeeBean.getAge());
  74.   employee.setEmpName(employeeBean.getName());
  75.   employee.setSalary(employeeBean.getSalary());
  76.   employee.setEmpId(employeeBean.getId());
  77.   employeeBean.setId(null);
  78.   return employee;
  79.  }
  80.  
  81.  private List<EmployeeBean> prepareListofBean(List<Employee> employees){
  82.   List<employeebean> beans = null;
  83.   if(employees != null && !employees.isEmpty()){
  84.    beans = new ArrayList<EmployeeBean>();
  85.    EmployeeBean bean = null;
  86.    for(Employee employee : employees){
  87.     bean = new EmployeeBean();
  88.     bean.setName(employee.getEmpName());
  89.     bean.setId(employee.getEmpId());
  90.     bean.setAddress(employee.getEmpAddress());
  91.     bean.setSalary(employee.getSalary());
  92.     bean.setAge(employee.getEmpAge());
  93.     beans.add(bean);
  94.    }
  95.   }
  96.   return beans;
  97.  }
  98.  
  99.  private EmployeeBean prepareEmployeeBean(Employee employee){
  100.   EmployeeBean bean = new EmployeeBean();
  101.   bean.setAddress(employee.getEmpAddress());
  102.   bean.setAge(employee.getEmpAge());
  103.   bean.setName(employee.getEmpName());
  104.   bean.setSalary(employee.getSalary());
  105.   bean.setId(employee.getEmpId());
  106.   return bean;
  107.  }
  108. }
Spring Web configuration file web.xml
  1. <web-app version="2.5" 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
  2.           http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  3.    <servlet>
  4.      <servlet-name>sdnext</servlet-name>
  5.      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  6.      <init-param>
  7.             <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
  8.      <load-on-startup>1</load-on-startup>
  9.    </servlet>
  10.  <servlet-mapping>
  11.   <servlet-name>sdnext</servlet-name>
  12.   <url-pattern>*.html</url-pattern>
  13.  </servlet-mapping>
  14.  <welcome-file-list>
  15.   <welcome-file>index.html</welcome-file>
  16.  </welcome-file-list>
  17. </web-app>

Spring Web configuration file sdnext-servlet.xml
  1. <beans xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
  2. http://www.springframework.org/schema/beans
  3. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  4. http://www.springframework.org/schema/context
  5. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  6. http://www.springframework.org/schema/tx
  7. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
  8. <context:property-placeholder location="classpath:resources/database.properties">
  9. </context:property-placeholder>
  10. <context:component-scan base-package="com.dineshonjava">
  11. </context:component-scan>
  12. <tx:annotation-driven transaction-manager="hibernateTransactionManager">
  13. </tx:annotation-driven>
  14. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">
  15.  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
  16.  <property name="prefix" value="/WEB-INF/views/"></property>
  17.  <property name="suffix" value=".jsp"></property>
  18. </bean>
  19. <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
  20.  <property name="driverClassName" value="${database.driver}"></property>
  21.  <property name="url" value="${database.url}"></property>
  22.  <property name="username" value="${database.user}"></property>
  23.  <property name="password" value="${database.password}"></property>
  24. </bean>
  25. <bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
  26.  <property name="dataSource" ref="dataSource"></property>
  27.  <property name="annotatedClasses">
  28.   <list>
  29.    <value>com.dineshonjava.model.Employee</value>
  30.   </list>
  31.  </property>
  32.  <property name="hibernateProperties">
  33.  <props>
  34.   <prop key="hibernate.dialect">${hibernate.dialect}</prop>
  35.   <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
  36.   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>    
  37.         </props>
  38.       </property>
  39. </bean>
  40.   <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager" id="hibernateTransactionManager">
  41.  <property name="sessionFactory" ref="sessionFactory"></property>
  42.   </bean>
  43. </beans>
addEmployee.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7.  <head>
  8.   <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  9.   <title>Spring MVC Form Handling</title>
  10.  </head>
  11.  <body>
  12.   <h2>Add Employee Data</h2>
  13.   <form:form method="POST" action="/sdnext/save.html">
  14.       <table>
  15.        <tr>
  16.            <td><form:label path="id">Employee ID:</form:label></td>
  17.            <td><form:input path="id" value="${employee.id}" readonly="true"/></td>
  18.        </tr>
  19.        <tr>
  20.            <td><form:label path="name">Employee Name:</form:label></td>
  21.            <td><form:input path="name" value="${employee.name}"/></td>
  22.        </tr>
  23.        <tr>
  24.            <td><form:label path="age">Employee Age:</form:label></td>
  25.            <td><form:input path="age" value="${employee.age}"/></td>
  26.        </tr>
  27.        <tr>
  28.            <td><form:label path="salary">Employee Salary:</form:label></td>
  29.            <td><form:input path="salary" value="${employee.salary}"/></td>
  30.        </tr>
  31.        
  32.        <tr>
  33.            <td><form:label path="address">Employee Address:</form:label></td>
  34.                     <td><form:input path="address" value="${employee.address}"/></td>
  35.        </tr>
  36.           <tr>
  37.          <td colspan="2"><input type="submit" value="Submit"/></td>
  38.         </tr>
  39.    </table>
  40.   </form:form>
  41.  
  42.   <c:if test="${!empty employees}">
  43.   <h2>List Employees</h2>
  44.  <table align="left" border="1">
  45.   <tr>
  46.    <th>Employee ID</th>
  47.    <th>Employee Name</th>
  48.    <th>Employee Age</th>
  49.    <th>Employee Salary</th>
  50.    <th>Employee Address</th>
  51.            <th>Actions on Row</th>
  52.   </tr>
  53.   <c:forEach items="${employees}" var="employee">
  54.    <tr>
  55.     <td><c:out value="${employee.id}"/></td>
  56.     <td><c:out value="${employee.name}"/></td>
  57.     <td><c:out value="${employee.age}"/></td>
  58.     <td><c:out value="${employee.salary}"/></td>
  59.     <td><c:out value="${employee.address}"/></td>
  60.     <td align="center"><a href="edit.html?id=${employee.id}">Edit</a> | <a href="delete.html?id=${employee.id}">Delete</a></td>
  61.    </tr>
  62.   </c:forEach>
  63.  </table>
  64. </c:if>
  65.  </body>
  66. </html>
employeesList.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <title>All Employees</title>
  8. </head>
  9. <body>
  10. <h1>List Employees</h1>
  11. <h3><a href="add.html">Add More Employee</a></h3>
  12. <c:if test="${!empty employees}">
  13.  <table align="left" border="1">
  14.   <tr>
  15.    <th>Employee ID</th>
  16.    <th>Employee Name</th>
  17.    <th>Employee Age</th>
  18.    <th>Employee Salary</th>
  19.    <th>Employee Address</th>
  20.   </tr>
  21.   <c:forEach items="${employees}" var="employee">
  22.    <tr>
  23.     <td><c:out value="${employee.id}"/></td>
  24.     <td><c:out value="${employee.name}"/></td>
  25.     <td><c:out value="${employee.age}"/></td>
  26.     <td><c:out value="${employee.salary}"/></td>
  27.     <td><c:out value="${employee.address}"/></td>
  28.    </tr>
  29.   </c:forEach>
  30.  </table>
  31. </c:if>
  32. </body>
  33. </html>
index.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5.   <head>
  6.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7.     <title>Spring3MVC with Hibernate3 CRUD Example using Annotations</title>
  8.   </head>
  9.   <body>
  10.     <h2>Spring3MVC with Hibernate3 CRUD Example using Annotations</h2>
  11.     <h2>1. <a href="employees.html">List of Employees</a></h2>
  12.     <h2>2. <a href="add.html">Add Employee</a></h2>
  13.   </body>
  14. </html>
Once you are done with creating source and configuration files, export your application. Right click on your application and useExport-> WAR File option and save your Spring3HibernateApp.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try a URL http://localhost:8080/sdnext/ and you should see the following result if everything is fine with your Spring Web Application: