Spring MVC Hibernate MySQL CRUD Operation:
The idea of MVC framework is to separate the business logic from front end and change them without affecting others.
Model: Represents data
View: User Interface of the application
Controller: Receives request and perform the operations
- The request is received by the dispatcher servlet
- The dispatcher Servlet checks with the Handler Mappings to determine the appropriate controller to pass the request
- The dispatcher Servlet get the appropriate controller from Handler Mapping and passes the request to Controller.
- The controller sends the request along with the object containing the name of the view and data to be displayed, but not the exact logical name
- Dispatcher Servlet after receiving the name, checks with view resolver to resolve the actual logical name.
- Finally the view is displayed to the user
Now let us see the example of Spring MVC, Hibernate with MySQL.
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
<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>SpringHibernate</groupId> <artifactId>SpringMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVC Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <java-version>1.6</java-version> <org.springframework-version>4.0.3.RELEASE</org.springframework-version> <org.aspectj-version>1.7.4</org.aspectj-version> <org.slf4j-version>1.7.5</org.slf4j-version> <hibernate.version>4.3.5.Final</hibernate.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- Apache Commons DBCP --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- Spring ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> <finalName>SpringMVC</finalName> </build> </project> |
Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.javainfinite.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue int id; String employeeName; String employeeContact; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeContact() { return employeeContact; } public void setEmployeeContact(String employeeContact) { this.employeeContact = employeeContact; } } |
EmployeeDAO
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.javainfinite.dao; import java.util.List; import com.javainfinite.model.Employee; public interface EmployeeDAO { public void saveEmployee(Employee employee); public void updateEmployee(Employee employee); public List<Employee> getAllEmployees(); public Employee getById(int id); public void deleteEmployee(int id); } |
EmployeeDAOImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package com.javainfinite.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.javainfinite.model.Employee; public class EmployeeDAOImpl implements EmployeeDAO { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void saveEmployee(Employee employee) { Session session = this.sessionFactory.openSession(); session.beginTransaction(); session.save(employee); session.getTransaction().commit(); session.close(); } public void updateEmployee(Employee employee) { Session session = this.sessionFactory.openSession(); session.beginTransaction(); session.update(employee); session.getTransaction().commit(); session.close(); } public List<Employee> getAllEmployees() { Session session = this.sessionFactory.openSession(); session.beginTransaction(); Query query = session.createQuery("From Employee"); @SuppressWarnings("unchecked") List<Employee> employeeList = query.list(); return employeeList; } public Employee getById(int id) { Session session = this.sessionFactory.openSession(); session.beginTransaction(); Employee employee = (Employee) session.load(Employee.class, new Integer(id)); session.getTransaction().commit(); return employee; } public void deleteEmployee(int id) { Session session = this.sessionFactory.openSession(); session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, new Integer(id)); session.delete(employee); session.getTransaction().commit(); session.close(); } } |
EmployeeService
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.javainfinite.service; import java.util.List; import com.javainfinite.model.Employee; public interface EmployeeService { public void saveEmployee(Employee employee); public void updateEmployee(Employee employee); public List<Employee> getAllEmployees(); public Employee getById(int id); public void deleteEmployee(int id); } |
EmployeeServiceImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.javainfinite.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.javainfinite.dao.EmployeeDAO; import com.javainfinite.model.Employee; public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDAO employeeDAO; public EmployeeDAO getEmployeeDAO() { return employeeDAO; } public void setEmployeeDAO(EmployeeDAO employeeDAO) { this.employeeDAO = employeeDAO; } public void saveEmployee(Employee employee) { this.employeeDAO.saveEmployee(employee); } public void updateEmployee(Employee employee) { this.employeeDAO.updateEmployee(employee); } public List<Employee> getAllEmployees() { return this.employeeDAO.getAllEmployees(); } public Employee getById(int id) { return this.employeeDAO.getById(id); } public void deleteEmployee(int id) { this.employeeDAO.deleteEmployee(id); } } |
EmployeeController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
package com.javainfinite.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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 com.javainfinite.model.Employee; import com.javainfinite.service.EmployeeService; @Controller public class EmployeeController { EmployeeService employeeService; public EmployeeService getEmployeeService() { return employeeService; } @Autowired public void setEmployeeService(EmployeeService employeeService) { this.employeeService = employeeService; } @RequestMapping(value = "/", method = RequestMethod.GET) public String getAllEmployees(Model model) { model.addAttribute("employee", new Employee()); model.addAttribute("employeeList", this.employeeService.getAllEmployees()); return "employee"; } @RequestMapping(value = "/employees", method = RequestMethod.GET) public String getAllEmployees1(Model model) { model.addAttribute("employee", new Employee()); model.addAttribute("employeeList", this.employeeService.getAllEmployees()); return "employee"; } @RequestMapping(value = "/employee/add", method = RequestMethod.POST) public String addEmployee(@ModelAttribute("employee") Employee employee) { this.employeeService.saveEmployee(employee); return "redirect:/employees"; } @RequestMapping(value = "/employee/update", method = RequestMethod.POST) public String updateEmployee(@ModelAttribute("employee") Employee employee) { this.employeeService.updateEmployee(employee); return "redirect:/employees"; } @RequestMapping(value = "/deleteEmployee/{id}") public String removeEmployee(@PathVariable("id") int id) { this.employeeService.deleteEmployee(id); return "redirect:/employees"; } @RequestMapping(value = "/editEmployee/{id}") public String editEmployee(@PathVariable("id") int id, Model model) { model.addAttribute("employee", this.employeeService.getById(id)); return "edit"; } } |
spring-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<beans:beans xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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-4.0.xsd"> <mvc:annotation-driven/> <mvc:default-servlet-handler /> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/View/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="com.javainfinite"/> <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost:3306/database1" /> <beans:property name="username" value="root" /> <beans:property name="password" value="root" /> </beans:bean> <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="annotatedClasses"> <beans:list> <beans:value>com.javainfinite.model.Employee</beans:value> </beans:list> </beans:property> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </beans:prop> <beans:prop key="hibernate.show_sql">true</beans:prop> <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop> <beans:prop key="hibernate.current_session_context_class">thread</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="employeeDAO" class="com.javainfinite.dao.EmployeeDAOImpl"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/> </beans:bean> <beans:bean id="EmployeeService" class="com.javainfinite.service.EmployeeServiceImpl"> <beans:property name="employeeDAO" ref="employeeDAO"/> </beans:bean> <tx:annotation-driven transaction-manager="transactionManager"/> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> </beans:beans> |
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<web-app version="2.5" 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"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
employee.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<%@ 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"%> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!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>Employee Page</title> </head> <body> <c:url var="addEmployee" value="/employee/add" ></c:url> <form:form action="${addEmployee }" commandName="employee"> <table> <tr> <td><form:label path="employeeName"> <spring:message text="Employee Name" /> </form:label></td> <td> <form:input path="employeeName" type="text"/></td> </tr> <tr> <td><form:label path="employeeContact"> <spring:message text="Employee Contact" /> </form:label></td> <td> <form:input path="employeeContact" type="text"/></td> <td> </tr> <tr> <td> <input type="submit" value="<spring:message text="Add Person"/>" /> </td> </tr> </table> <table border="1"> <tr> <th> Employee Id </th> <th> Employee Name </th> <th> Employee Contact </th> <th> Operation </th> </tr> <c:if test="${!empty employeeList}"> <c:forEach items="${employeeList}" var="employee"> <tr> <td>${employee.id }</td> <td>${employee.employeeName }</td> <td>${employee.employeeContact }</td> <td><a href="<c:url value='/deleteEmployee/${employee.id}' />" >Delete</a></td> <td><a href="<c:url value='/editEmployee/${employee.id}' />" >Edit</a></td> </tr> </c:forEach> </c:if> </table> </form:form> </body> </html> |
edit.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<%@ 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"%> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!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></title> </head> <body> <c:url var="updateEmployee" value='/employee/update' /> <form:form action="${updateEmployee }" commandName="employee"> <table> <tr> <td><form:label path="id"> <spring:message text="Id" /> </form:label></td> <td> <form:input path="id" type="text"/></td> </tr> <tr> <td><form:label path="employeeName"> <spring:message text="Employee Name" /> </form:label></td> <td> <form:input path="employeeName" type="text"/></td> </tr> <tr> <td><form:label path="employeeContact"> <spring:message text="Employee Contact" /> </form:label></td> <td> <form:input path="employeeContact" type="text"/></td> <td> </tr> <tr> <td> <input type="submit" value="<spring:message text="Update Person"/>" /> </td> </tr> </table> </form:form> </body> </html> |
Deleting Alpha record,