Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Spring MVC With Hibernate Example, Hibernate and Spring MVC Tutorials

Create Spring MVC Project with Maven and your pom.xml should be like this

Download Full Code from here

<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>com.springmvcpractice</groupId>

<artifactId>springmvcpractice</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>springmvcpractice Maven Webapp</name>

<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>8</maven.compiler.source>

<maven.compiler.target>8</maven.compiler.target>

<java.version>1.8</java.version>

<spring.version>5.3.33</spring.version>

</properties>


<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.13.1</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>${spring.version}</version>

</dependency>

<!-- ================= SPRING ORM (Hibernate Integration) ================= -->

<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>


<!-- ================= HIBERNATE CORE ================= -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.6.15.Final</version>

</dependency>


<!-- ================= HIBERNATE ENTITY MANAGER (JPA) ================= -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-entitymanager</artifactId>

<version>5.6.15.Final</version>

</dependency>


<!-- ================= JPA API ================= -->

<dependency>

<groupId>javax.persistence</groupId>

<artifactId>javax.persistence-api</artifactId>

<version>2.2</version>

</dependency>


<!-- ================= DATABASE DRIVER (MySQL 8) ================= -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>


<!-- ================= HIBERNATE VALIDATOR (OPTIONAL) ================= -->

<dependency>

<groupId>org.hibernate.validator</groupId>

<artifactId>hibernate-validator</artifactId>

<version>6.2.5.Final</version>

</dependency>



<!-- JSTL for JSP pages -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>


<!-- Servlet API -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>4.0.1</version>

<scope>provided</scope>

</dependency>

</dependencies>


<build>

<finalName>springmvcpractice</finalName>

<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->

<plugins>

<plugin>

<artifactId>maven-clean-plugin</artifactId>

<version>3.4.0</version>

</plugin>

<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->

<plugin>

<artifactId>maven-resources-plugin</artifactId>

<version>3.3.1</version>

</plugin>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.13.0</version>

</plugin>

<plugin>

<artifactId>maven-surefire-plugin</artifactId>

<version>3.3.0</version>

</plugin>

<plugin>

<artifactId>maven-war-plugin</artifactId>

<version>3.4.0</version>

</plugin>

<plugin>

<artifactId>maven-install-plugin</artifactId>

<version>3.1.2</version>

</plugin>

<plugin>

<artifactId>maven-deploy-plugin</artifactId>

<version>3.1.2</version>

</plugin>

</plugins>

</pluginManagement>

</build>

</project>


step2nd:


create disptacher servlet like this


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:mvc="http://www.springframework.org/schema/mvc"

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"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- Scan your single package -->

<context:component-scan base-package="com.scs.controllers"/>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven/>


<!-- ✅ DATASOURCE (MANDATORY) -->

<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>

<property name="url"

value="jdbc:mysql://localhost:3306/mydb?useSSL=false&amp;serverTimezone=UTC"/>

<property name="username" value="root"/>

<property name="password" value=""/>

</bean>


<!-- ✅ SESSION FACTORY -->

<bean id="sessionFactory"

class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"/>

<property name="configLocation" value="classpath:hibernate.cfg.xml"/>

</bean>


<!-- ✅ TRANSACTION MANAGER -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate5.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"/>

</bean>


<tx:annotation-driven/>


<!-- View resolver -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/"/>

<property name="suffix" value=".jsp"/>

</bean>


</beans>


step 3rd:


Web.xml


<!DOCTYPE web-app PUBLIC

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>



<servlet>

<servlet-name>scs</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/scs-servlet.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>scs</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>



step 4th hibernate.cfg.xml and it must be under /src/main/resources


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


<hibernate-configuration>

<session-factory>


<!-- ONLY Hibernate settings -->

<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<property name="hibernate.show_sql">true</property>

<property name="hibernate.format_sql">true</property>

<property name="hibernate.hbm2ddl.auto">update</property>


<mapping class="com.scs.controllers.Employee"/>


</session-factory>

</hibernate-configuration>



step5th:


create model class for hibernate


package com.scs.controllers; import java.io.Serializable; import javax.persistence.*; @Entity @Table(name="employee") public class Employee implements Serializable{ private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) 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; } }




step6:
create EmpDao interface

package com.scs.controllers;

import java.util.*;

public interface EmployeeDao {

public void addEmployee(Employee employee);

public List<Employee> listEmployeess();

public Employee getEmployee(int empid);

public void deleteEmployee(Employee employee);

}



step7:


create EmpDao Implementation


package com.scs.controllers;


import java.util.List;


import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

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();

}

}


step7:


Create Empbean class

package com.scs.controllers;


public class EmpBean {

private Integer id;

private String name;

private Integer age;

private Long salary;

private String address;

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 Long getSalary() {

return salary;

}

public void setSalary(Long salary) {

this.salary = salary;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}


}


step9:

Create EmpService Interface


package com.scs.controllers;


import java.util.List;


public interface EmployeeService {

public void addEmployee(Employee employee);

public List<Employee> listEmployeess();

public Employee getEmployee(int empid);

public void deleteEmployee(Employee employee);

}


step 10:


Create EmpServiceImpl Class


package com.scs.controllers; 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; @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); } }



step11:

create controller:

package com.scs.controllers;


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.GetMapping;

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;


@Controller

public class EmployeeController {

@Autowired

private EmployeeService employeeService;

@GetMapping(value = "/emp")

public ModelAndView Employee() {

return new ModelAndView("addemp","command",new EmpBean());

}

@RequestMapping(value = "/save", method = RequestMethod.POST)

public ModelAndView saveEmployee(@ModelAttribute("command")EmpBean employeeBean,

BindingResult result) {

Employee employee = prepareModel(employeeBean);

employeeService.addEmployee(employee);

return new ModelAndView("addemp","command",new EmpBean());

}

private Employee prepareModel(EmpBean 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;

}

@RequestMapping(value="/employees", method = RequestMethod.GET)

public ModelAndView listEmployees() {

System.out.println("size is "+employeeService.listEmployeess().size());

return new ModelAndView("employeesList").addObject("empdata",prepareListofBean(employeeService.listEmployeess()));

}

private List<EmpBean> prepareListofBean(List<Employee> employees){

List<EmpBean> beans = null;

if(employees != null && !employees.isEmpty()){

beans = new ArrayList<EmpBean>();

EmpBean bean = null;

for(Employee employee : employees){

bean = new EmpBean();

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;

}

}



create views under views folder


addemp.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="save">

<table>

<tr>

<td><form:label path="id">Employee ID:</form:label></td>

<td><form:input path="id" readonly="true"/></td>

</tr>

<tr>

<td><form:label path="name">Employee Name:</form:label></td>

<td><form:input path="name" /></td>

</tr>

<tr>

<td><form:label path="age">Employee Age:</form:label></td>

<td><form:input path="age" /></td>

</tr>

<tr>

<td><form:label path="salary">Employee Salary:</form:label></td>

<td><form:input path="salary" /></td>

</tr>

<tr>

<td><form:label path="address">Employee Address:</form:label></td>

<td><form:input path="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=UTF-8"

pageEncoding="UTF-8" isELIgnored="false" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<h1>List Employees</h1>

<h3><a href="emp">Add More Employee</a></h3>


<c:if test="${!empty empdata}">

<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="${empdata}" 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>



Post a Comment

0 Comments