Skip to main content

Spring MVC With Hibernate Example, Hibernate and Spring MVC Tutorials



Step1st:-
Create Table:-
CREATE TABLE Employee(
   EMPID   INT NOT NULL AUTO_INCREMENT,
   EMPNAME VARCHAR(20) NOT NULL,
   EMPAGE  INT NOT NULL,
   SALARY BIGINT NOT NULL,
   ADDRESS VARCHAR(20) NOT NULL
   PRIMARY KEY (ID)
);
Step2nd:-  Create hibernate.cfg.xml
Step3rd:-  Add Jar File under lib folder
Step4th:-  Create Dispatcher servlet and add it into web.xml
step5h:-Create EmployeeBean.java
public class EmployeeBean {
 private Integer id;
 private String name;
 private Integer age;
 private Long salary;
 private String address;

 public Long getSalary() {
  return salary;
 }
 public void setSalary(Long salary) {
  this.salary = salary;
 }
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
Employee.java
import java.io.Serializable;
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 implements Serializable{

 private static final long serialVersionUID = -723583058586873479L;

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 @Column(name = "empid")
 private Integer empId;

 @Column(name="empname")
 private String empName;
 @Column(name="empaddress")
 private String empAddress;
 @Column(name="salary")
 private Long salary;
 @Column(name="empAge")
 private Integer empAge;
 public Integer getEmpId() {
  return empId;
 }
 public void setEmpId(Integer empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getEmpAddress() {
  return empAddress;
 }
 public void setEmpAddress(String empAddress) {
  this.empAddress = empAddress;
 }
 public Long getSalary() {
  return salary;
 }
 public void setSalary(Long salary) {
  this.salary = salary;
 }
 public Integer getEmpAge() {
  return empAge;
 }
 public void setEmpAge(Integer empAge) {
  this.empAge = empAge;
 }
}
EmployeeDao.java
import java.util.List;
import com.dineshonjava.model.Employee;
/**
 * @author Dinesh Rajput
 *
 */
public interface EmployeeDao {
 public void addEmployee(Employee employee);
 public List<Employee> listEmployeess();
 public Employee getEmployee(int empid);
 public void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dineshonjava.model.Employee;
/**
 * @author Dinesh Rajput
 *
 */
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
 @Autowired
 private SessionFactory sessionFactory;
 public void addEmployee(Employee employee) {
   sessionFactory.getCurrentSession().saveOrUpdate(employee);
 }
 @SuppressWarnings("unchecked")
 public List<Employee> listEmployeess() {
  return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
 }
 public Employee getEmployee(int empid) {
  return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
 }
 public void deleteEmployee(Employee employee) {
  sessionFactory.getCurrentSession().createQuery("DELETE FROM Employee WHERE empid = "+employee.getEmpId()).executeUpdate();
 }
}
EmployeeService.java
import java.util.List;
import com.dineshonjava.model.Employee;
/**
 * @author Dinesh Rajput
 *
 */
public interface EmployeeService {
 public void addEmployee(Employee employee);
 public List<Employee> listEmployeess();
 public Employee getEmployee(int empid);
 public void deleteEmployee(Employee employee);
}
EmployeeServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.dineshonjava.dao.EmployeeDao;
import com.dineshonjava.model.Employee;
/**
 * @author Dinesh Rajput
 *
 */
@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
 @Autowired
 private EmployeeDao employeeDao;
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
 public void addEmployee(Employee employee) {
  employeeDao.addEmployee(employee);
 }
 public List<Employee> listEmployeess() {
  return employeeDao.listEmployeess();
 }
 public Employee getEmployee(int empid) {
  return employeeDao.getEmployee(empid);
 }
 public void deleteEmployee(Employee employee) {
  employeeDao.deleteEmployee(employee);
 }
}
EmployeeController.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.dineshonjava.bean.EmployeeBean;
import com.dineshonjava.model.Employee;
import com.dineshonjava.service.EmployeeService;
/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class EmployeeController {
 @Autowired
 private EmployeeService employeeService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
   BindingResult result) {
  Employee employee = prepareModel(employeeBean);
  employeeService.addEmployee(employee);
  return new ModelAndView("redirect:/add.html");
 }
 @RequestMapping(value="/employees", method = RequestMethod.GET)
 public ModelAndView listEmployees() {
  Map<String Object> model = new HashMap<String Object>();
  model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  return new ModelAndView("employeesList", model);
 }
 @RequestMapping(value = "/add", method = RequestMethod.GET)
 public ModelAndView addEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
   BindingResult result) {
  Map<String, Object> model = new HashMap<String, Object>();
  model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  return new ModelAndView("addEmployee", model);
 }
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
  return new ModelAndView("index");
 }
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView editEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
   BindingResult result) {
  employeeService.deleteEmployee(prepareModel(employeeBean));
  Map<String, Object> model = new HashMap<String, Object>();
  model.put("employee", null);
  model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  return new ModelAndView("addEmployee", model);
 }
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView deleteEmployee(@ModelAttribute("command")EmployeeBean employeeBean,
   BindingResult result) {
  Map<String, Object> model = new HashMap<String, Object>();
  model.put("employee", prepareEmployeeBean(employeeService.getEmployee(employeeBean.getId())));
  model.put("employees",  prepareListofBean(employeeService.listEmployeess()));
  return new ModelAndView("addEmployee", model);
 }
 private Employee prepareModel(EmployeeBean employeeBean){
  Employee employee = new Employee();
  employee.setEmpAddress(employeeBean.getAddress());
  employee.setEmpAge(employeeBean.getAge());
  employee.setEmpName(employeeBean.getName());
  employee.setSalary(employeeBean.getSalary());
  employee.setEmpId(employeeBean.getId());
  employeeBean.setId(null);
  return employee;
 }
 private List<EmployeeBean> prepareListofBean(List<Employee> employees){
  List<employeebean> beans = null;
  if(employees != null && !employees.isEmpty()){
   beans = new ArrayList<EmployeeBean>();
   EmployeeBean bean = null;
   for(Employee employee : employees){
    bean = new EmployeeBean();
    bean.setName(employee.getEmpName());
    bean.setId(employee.getEmpId());
    bean.setAddress(employee.getEmpAddress());
    bean.setSalary(employee.getSalary());
    bean.setAge(employee.getEmpAge());
    beans.add(bean);
   }
  }
  return beans;
 }
 private EmployeeBean prepareEmployeeBean(Employee employee){
  EmployeeBean bean = new EmployeeBean();
  bean.setAddress(employee.getEmpAddress());
  bean.setAge(employee.getEmpAge());
  bean.setName(employee.getEmpName());
  bean.setSalary(employee.getSalary());
  bean.setId(employee.getEmpId());
  return bean;
 }
}
addEmployee.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Spring MVC Form Handling</title>
 </head>
 <body>
  <h2>Add Employee Data</h2>
  <form:form method="POST" action="/sdnext/save.html">
      <table>
       <tr>
           <td><form:label path="id">Employee ID:</form:label></td>
           <td><form:input path="id" value="${employee.id}" readonly="true"/></td>
       </tr>
       <tr>
           <td><form:label path="name">Employee Name:</form:label></td>
           <td><form:input path="name" value="${employee.name}"/></td>
       </tr>
       <tr>
           <td><form:label path="age">Employee Age:</form:label></td>
           <td><form:input path="age" value="${employee.age}"/></td>
       </tr>
       <tr>
           <td><form:label path="salary">Employee Salary:</form:label></td>
           <td><form:input path="salary" value="${employee.salary}"/></td>
       </tr>      
       <tr>
           <td><form:label path="address">Employee Address:</form:label></td>
                    <td><form:input path="address" value="${employee.address}"/></td>
       </tr>
          <tr>
         <td colspan="2"><input type="submit" value="Submit"/></td>
        </tr>
   </table>
  </form:form>
  <c:if test="${!empty employees}">
  <h2>List Employees</h2>
 <table align="left" border="1">
  <tr>
   <th>Employee ID</th>
   <th>Employee Name</th>
   <th>Employee Age</th>
   <th>Employee Salary</th>
   <th>Employee Address</th>
           <th>Actions on Row</th>
  </tr>
  <c:forEach items="${employees}" var="employee">
   <tr>
    <td><c:out value="${employee.id}"/></td>
    <td><c:out value="${employee.name}"/></td>
    <td><c:out value="${employee.age}"/></td>
    <td><c:out value="${employee.salary}"/></td>
    <td><c:out value="${employee.address}"/></td>
    <td align="center"><a href="edit.html?id=${employee.id}">Edit</a> | <a href="delete.html?id=${employee.id}">Delete</a></td>
   </tr>
  </c:forEach>
 </table>
</c:if>
 </body>
</html>
EmployeeList.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>All Employees</title>
</head>
<body>
<h1>List Employees</h1>
<h3><a href="add.html">Add More Employee</a></h3>

<c:if test="${!empty employees}">
 <table align="left" border="1">
  <tr>
   <th>Employee ID</th>
   <th>Employee Name</th>
   <th>Employee Age</th>
   <th>Employee Salary</th>
   <th>Employee Address</th>
  </tr>

  <c:forEach items="${employees}" var="employee">
   <tr>
    <td><c:out value="${employee.id}"/></td>
    <td><c:out value="${employee.name}"/></td>
    <td><c:out value="${employee.age}"/></td>
    <td><c:out value="${employee.salary}"/></td>
    <td><c:out value="${employee.address}"/></td>
   </tr>
  </c:forEach>
 </table>
</c:if>
</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Spring3MVC with Hibernate3 CRUD Example using Annotations</title>
  </head>
  <body>
    <h2>Spring3MVC with Hibernate3 CRUD Example using Annotations</h2>
    <h2>1. <a href="employees.html">List of Employees</a></h2>
    <h2>2. <a href="add.html">Add Employee</a></h2>
  </body>
</html>

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...