Spring MVC-CRUD-Example-Hibernate-MySql-Maven-Bootstrap

Spring MVC CRUD application with Hibernate MySQL Maven integration
This is a basic application in Spring MVC which performs
CRUD(Create,Read,Update,Delete) operation.CRUD operation is the base of any application.In this example Hibernate is used with MySQL for database interaction.Maven is used as a build tool.CRUD operation will be performed on Employee entity.
1- Create Maven Project .
2-Delete web.xml as we are doing all configuration in java classes.
3- Copy pom.xml from previous example and replace (<artifactId>CrudApp</artifactId>, <name>CrudApp Maven Webapp</name>, <finalName>CrudApp</finalName>, <warName>CrudApp</warName> ) in pom.xml as these tags are project dependent.
4-Copy application.properties from resources and Spring - Hibernate Configuration File from the previous example (com.skuera.config) package.
Below is rest code for the application.
Dao Layer
This layer in the Spring MVC application contain all the classes which interact with the database using the Hibernate session factory ,session, and transaction.
DaoI.java
package com.skuera.dao;
import java.util.List;
import com.skuera.entity.Dept;
import com.skuera.entity.Employee;
public interface DaoI {
public List<Employee> getEmployee();
public List<Dept> getDept();
public Employee getEmployeeById(int eid);
public Dept getDeptById(int deptId);
public int saveEmployee(Employee emp);
public int deleteEmployee(Employee emp);
public int updateEmployee(Employee emp);
}
DaoImpl.java
package com.skuera.dao;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.skuera.entity.Dept;
import com.skuera.entity.Employee;
/**
* @author skuera
*
*/
@Repository
@Transactional
public class DaoImpl implements DaoI {
@Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<Employee> getEmployee() {
String hql="from Employee e";
List<Employee> elist= (List<Employee>) sessionFactory.getCurrentSession().createQuery(hql).list();
return elist;
}
@Override
public Employee getEmployeeById(int eid) {
Employee employee=(Employee) sessionFactory.getCurrentSession().get(Employee.class,eid);
if(employee!=null){
Hibernate.initialize(employee.getDepartment());
}
return employee;
}
@Override
@Transactional
public int saveEmployee(Employee emp) {
try{
sessionFactory.getCurrentSession().save(emp);
return 1;
}catch(DataAccessException e){
return 0;
}
}
@Override
public int deleteEmployee(Employee emp) {
sessionFactory.getCurrentSession().delete(emp);
return 1;
}
@Override
public int updateEmployee(Employee emp) {
sessionFactory.getCurrentSession().merge(emp);
return 1;
}
@Override
public List<Dept> getDept() {
String hql="from Dept d";
List<Dept> elist= (List<Dept>) sessionFactory.getCurrentSession().createQuery(hql).list();
return elist;
}
@Override
public Dept getDeptById(int deptId) {
Dept dep=(Dept) sessionFactory.getCurrentSession().load(Dept.class,deptId);
return dep;
}
}
Service Layer
This is service layer in which we manipulate data received from the controller and transfer that to dao layer.Sometimes we use this layer for writing business logics.
SerI.java
package com.skuera.service;
import java.util.List;
import com.skuera.entity.Dept;
import com.skuera.entity.Employee;
public interface SerI {
public List<Employee> getEmployee();
public List<Dept> getDept();
public Employee getEmployeeById(int eid);
public int saveEmployee(Employee emp);
public int deleteEmployee(int emp);
public int updateEmployee(Employee emp);
}
package com.skuera.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.skuera.dao.DaoI;
import com.skuera.entity.Dept;
import com.skuera.entity.Employee;
@Service
@Transactional
public class SerImpl implements SerI{
@Autowired
private DaoI dao;
public void setDao(DaoI dao) {
this.dao = dao;
}
@Override
public List<Employee> getEmployee() {
// TODO Auto-generated method stub
return dao.getEmployee();
}
@Override
public Employee getEmployeeById(int eid) {
// TODO Auto-generated method stub
return dao.getEmployeeById(eid);
}
@Override
public int saveEmployee(Employee emp) {
// TODO Auto-generated method stub
Dept dept=dao.getDeptById(emp.getDepartment().getDeptId());
emp.setDepartment(dept);
return dao.saveEmployee(emp);
}
@Override
public int deleteEmployee(int emp) {
// TODO Auto-generated method stub
return dao.deleteEmployee(dao.getEmployeeById(emp));
}
@Override
public int updateEmployee(Employee emp) {
// TODO Auto-generated method stub
return dao.updateEmployee(emp);
}
@Override
public List<Dept> getDept() {
// TODO Auto-generated method stub
return dao.getDept();
}
}
Controller Layer
This layer mainly handles all the request coming from the use and transfer that to the service layer .It also gets response from service and passes that to the view layer.
package com.skuera.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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 org.springframework.web.servlet.ModelAndView;
import com.skuera.entity.Dept;
import com.skuera.entity.Employee;
import com.skuera.service.SerI;
/**
* @author skuera
*
*/
@Controller
public class EmployeeController {
@Autowired
private SerI ser;
public void setSer(SerI ser) {
this.ser = ser;
}
@RequestMapping(method=RequestMethod.GET,value="/emplist.do")
public String getEmployeeList(HttpServletRequest request,HttpServletResponse response,Model model){
HttpSession sess=request.getSession();
List<Employee> empList=new ArrayList<>();
empList = ser.getEmployee();
sess.setAttribute("emplist",empList);
return "empList";
}
@RequestMapping(method=RequestMethod.GET,value="/addemp.do")
public String getAddEmployee(HttpServletRequest request,HttpServletResponse response,ModelMap model){
HttpSession sess=request.getSession();
System.out.println("Shashi");
Map<Integer,String> dept=new HashMap<>();
List<Dept> deptList=ser.getDept();
for(Dept d:deptList){
dept.put(d.getDeptId(),d.getDeptName());
}
Employee emp=new Employee();
model.addAttribute("emp", emp);
sess.setAttribute("eDept", dept);
model.addAttribute("edit", false);
return "addEmp";
}
@RequestMapping(method=RequestMethod.POST,value="/addemp.do")
public ModelAndView AddEmployee(@ModelAttribute("emp") Employee emp){
ser.saveEmployee(emp);
return new ModelAndView("redirect:emplist.do");
}
@RequestMapping(value = { "/edit-emp-{empId}" }, method = RequestMethod.GET)
public String editEmployee(@PathVariable Integer empId, Model model) {
Employee emp=new Employee();
emp = ser.getEmployeeById(empId);
model.addAttribute("emp", emp);
model.addAttribute("edit", true);
return "addEmp";
}
@RequestMapping(value = { "/edit-emp-{empId}" }, method = RequestMethod.POST)
public ModelAndView updateStudent(@ModelAttribute("emp") Employee emp,Model model) {
System.out.println(emp.geteId()+"$$$");
ser.updateEmployee(emp);
model.addAttribute("emp", emp);
return new ModelAndView("redirect:emplist.do");
}
@RequestMapping(value = { "/delete-emp-{empId}" }, method = RequestMethod.GET)
public ModelAndView deleteEmployee(@PathVariable Integer empId, Model model) {
ser.deleteEmployee(empId);
return new ModelAndView("redirect:emplist.do");
}
}
Model Layer
Dept.java
package com.skuera.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author skuera
*
*/
@Entity
@Table(name="dept")
public class Dept {
@Id
@GeneratedValue
@Column(name="dept_id")
private int deptId;
@Column(name="dept_name")
private String deptName;
@OneToMany(targetEntity = Employee.class, cascade = CascadeType.ALL, mappedBy = "department")
private Set<Employee> empoyees;
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Set<Employee> getEmpoyees() {
return empoyees;
}
public void setEmpoyees(Set<Employee> empoyees) {
this.empoyees = empoyees;
}
}
package com.skuera.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
/**
* @author skuera
*
*/
@Entity
@Table(name="employee")
public class Employee{
@Id
@GeneratedValue
@Column(name="emp_id")
private int eId;
@Column(name="emp_name")
private String eName;
@Column(name="emp_gender")
private int eGender;
@ManyToOne
@JoinColumn(name = "dept_id", referencedColumnName = "dept_id")
private Dept department;
public int geteId() {
return eId;
}
public void seteId(int eId) {
this.eId = eId;
}
public String geteName() {
return eName;
}
public void seteName(String eName) {
this.eName = eName;
}
public int geteGender() {
return eGender;
}
public void seteGender(int eGender) {
this.eGender = eGender;
}
public Dept getDepartment() {
return department;
}
public void setDepartment(Dept department) {
this.department = department;
}
}
Jsp Pages
addEmp.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel = "stylesheet">
<script src = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body >
<div class="container" >
<div class="well lead">Add Employee</div>
<form:form method="post" modelAttribute="emp" class="form-horizontal">
<form:input type="hidden" path="eId" id="eId"/>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="eName">Employee Name</label>
<div class="col-md-7">
<form:input type="text" path="eName" class="form-control input-sm" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="eGender">Status</label>
<div class="col-md-7">
<form:radiobutton path="eGender" value="0" />Male
<form:radiobutton path="eGender" value="1"/>Female
<div class="has-error">
<form:errors path="eGender" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="department">Dept</label>
<div class="col-md-7">
<form:select path="department.deptId" items="${eDept}" class="form-control input-sm" />
<div class="has-error">
<form:errors path="department" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-actions floatLeft">
<input type="submit" value="Save" id="btn" class="btn btn-primary btn-sm"/>
<input type="reset" value="Reset" class="btn btn-primary btn-sm"/>
</div>
</div>
</form:form>
</div>
</body>
</html>
empList.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel = "stylesheet">
<script src = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="generic-container">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading"><span class="lead">Employees</span></div>
<table class="table table-hover">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Gender</th>
<th>Department</th>
<th width="100"></th>
<th width="100"></th>
</tr>
</thead>
<tbody>
<c:forEach items="${emplist}" var="em">
<tr>
<td>${em.eId}</td>
<td>${em.eName}</td>
<c:choose>
<c:when test="${em.eGender==1}">
<td>Female</td>
<br />
</c:when>
<c:otherwise>
<td>Male</td>
<br />
</c:otherwise>
</c:choose>
<td>${em.department.deptName}</td>
<td><a href="<c:url value='/edit-emp-${em.eId}' />" class="btn btn-success
custom-width">edit</a></td>
<td><a href="<c:url value='/delete-emp-${em.eId}' />" class="btn btn-danger
custom-width">delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="well">
<a href="<c:url value='/addemp.do' />">Add New Employee</a>
</div>
</div>
</body>
</html>
index.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel = "stylesheet">
<script src = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="./static/css/app.css" rel="stylesheet"></link>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand">Employee Management</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="emplist.do">View Employee</a></li>
<li><a href="addemp.do">Add Employee</a></li>
</ul>
</div>
</nav>
</body>
</html>
The full code can be downloaded from Github.
Give you suggestion in comments.If you like the post Share with your friends on social network.
You may be interested in: Send Mail in Spring MVC using Gmail SMTP.
Spring MVC-CRUD-Example-Hibernate-MySql-Maven-Bootstrap
Reviewed by JavaInstance
on
8:38:00 AM
Rating:
Reviewed by JavaInstance
on
8:38:00 AM
Rating:



No comments: