Sep 17, 2015

CRUD - Spring4 MVC and Hibernate4 Example

 
Database Setup
 
 
-- Dumping database structure for springhibernate_db
CREATE DATABASE IF NOT EXISTS `springhibernate_db`;
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: ~2 rows (approximately)
INSERT INTO `employee` (`id`, `first_name`, `last_name`, `email`, `phone`) VALUES
(10, 'Nadha', 'Muni', 'muni@abcd.com', '89876787890'),
(11, 'Raghu', 'Ram', 'ram@xyz.com', '89898989898');


                                                                     pom.xml

<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"&gt;
 <modelVersion>4.0.0</modelVersion>
 <groupId>Spring4MVCHibernate4</groupId>
 <artifactId>Spring4MVCHibernate4</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>Spring4MVCHibernate4</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.6</jdk.version>
  <context.path>Spring4MVCHibernate4</context.path>
 </properties>
 <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>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.0</version>
  </dependency>
  <!-- Spring Hibernate Jar Start -->
  <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>
  <!-- Spring Hibernate Jar End -->
 </dependencies>
</project>
                                                                    web.xml

<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>Spring4MVCHibernate4</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\com\springdemo\controller\EmpController.java

package com.springdemo.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.springdemo.domain.Employee;
import com.springdemo.services.EmpService;
@Controller
public class EmpController {
 @Autowired
 EmpService empService;
 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Employee employee) {
  return new ModelAndView("form");
 }
 @RequestMapping("register")
 public ModelAndView registerUser(@ModelAttribute Employee employee) {
  empService.insertRow(employee);
  return new ModelAndView("redirect:list");
 }
 @RequestMapping("list")
 public ModelAndView getList() {
  List employeeList = empService.getList();
  return new ModelAndView("list", "employeeList", employeeList);
 }
 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  empService.deleteRow(id);
  return new ModelAndView("redirect:list");
 }
 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Employee employee) {
  Employee employeeObject = empService.getRowById(id);
  return new ModelAndView("edit", "employeeObject", employeeObject);
 }
 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Employee employee) {
  empService.updateRow(employee);
  return new ModelAndView("redirect:list");
 }
}

                                         \src\com\springdemo\domain\Employee.java

package com.springdemo.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int id;
 @Column(name = "first_name")
 private String firstName;

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

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

 @Column(name = "phone")
 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\com\springdemo\dao\EmpDao.java

package com.springdemo.dao;

import java.util.List;
import com.springdemo.domain.Employee;

public interface EmpDao {
 public void insertRow(Employee employee);
 public List getList();
 public Employee getRowById(int id);
 public void updateRow(Employee employee);
 public void deleteRow(int id);
}

                                    \src\com\springdemo\dao\EmpDaoImpl.java

 package com.springdemo.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.springdemo.domain.Employee;
@Repository
public class EmpDaoImpl implements EmpDao {
 @Autowired
 SessionFactory session;
 @Override
 public void insertRow(Employee employee) {
  session.getCurrentSession().save(employee);
 }
 @Override
 public List getList() {
  @SuppressWarnings("unchecked")
  List employeeList = session.getCurrentSession().createQuery("from Employee").list();
  return employeeList;
 }

 @Override
 public Employee getRowById(int id) {
  Employee employee = (Employee) session.getCurrentSession().get(Employee.class, id);
  return employee;
 }
 @Override
 public void updateRow(Employee employee) {
  session.getCurrentSession().saveOrUpdate(employee);
 }
 @Override
 public void deleteRow(int id) {
  Employee employee = (Employee) session.getCurrentSession().load(Employee.class, id);
  session.getCurrentSession().delete(employee);
 }
}

                                      \src\com\springdemo\services\EmpService.java

 package com.springdemo.services;
import java.util.List;
import com.springdemo.domain.Employee;
public interface EmpService {
 public void insertRow(Employee employee);
 public List getList();
 public Employee getRowById(int id);
 public void updateRow(Employee employee);
 public void deleteRow(int id);
}

                                     \src\com\springdemo\services\EmpServiceImpl.java


 package com.springdemo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.springdemo.dao.EmpDao;
import com.springdemo.domain.Employee;
@Service
public class EmpServiceImpl implements EmpService {
 @Autowired
 EmpDao empDao;
 @Transactional
 public void insertRow(Employee employee) {
  empDao.insertRow(employee);
 }
 @Transactional
 public List getList() {
  return empDao.getList();
 }

 @Transactional
 public Employee getRowById(int id) {
  return empDao.getRowById(id);
 }
 @Transactional
 public void updateRow(Employee employee) {
  empDao.updateRow(employee);
 }
 @Transactional
 public void deleteRow(int id) {
  empDao.deleteRow(id);
 }
}


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

<%@ 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"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Registration Form</title>
</head>
<body>
 <center>
  <div style="color: teal; font-size: 30px">User 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 View User List</a>
 </center>
</body>
</html>


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

<%@ 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"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Details</title>
</head>
<body>
 <center>
  <div style="color: teal; font-size: 30px">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\edit.jsp

<%@ 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"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit User Details</title>
</head>
<body>
 <center>
  <div style="color: teal; font-size: 30px">Edit User Details</div>
  <c:url var="userRegistration" value="saveUser.html" />
  <form:form id="registerForm" modelAttribute="employee" method="post" action="update">
  <input type="hidden" id="id" name="id" value="${employeeObject.id}">
   <table width="400px" height="150px">
<%--     <tr>
     <td><form:label path="id">First Name</form:label></td>
     <td><form:input path="id" value="${employeeObject.id}" /></td>
    </tr> --%>
    <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

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


                                               /src/main/resources/database.properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/springhibernate_db
database.user=root
database.password=password
hibernate.show_sql=true


 Output


 
 
Thank You !
 

 

No comments: