CRUD operations Tutorial using Java Spring, Hibernate and MySQL

(490 Views)


This tutorial aims at creating a Dynamic Web Application using Java Spring which implements CRUD(Create - Read - Update - Delete) operations in MySQL database through hibernate.

We will use the following for this tutorial:
  • Netbeans 8.0 IDE
  • Apache Tomcat 8 ( Version 9 work with netbeans V8.2+)
  • MySQL
  • Spring
  • Hibernate 4

Setting up the database:

Create table student in database tutorial in MySql:

create database tutorial; use tutorial; create table student( roll int primary key, name varchar(30) not null, school varchar(30) not null );

Setting up project in Netbeans:

  1. Create a new project under web application and name it "webApplication".
    new project under web application in Spring Project CRUD operations Tutorial with Hibernate and mysql

  2. Under Server selection, select Apache Tomcat 8.
    Apache Tomcat 8 in Spring Project CRUD operations Tutorial with Hibernate and mysql

  3. Under Frameworks, select Spring and Hibernate.
    select Spring and Hibernate in Spring Project CRUD operations Tutorial with Hibernate and mysql

When you create new project, web.xml file is generated in WEB-INF folder. When application starts, web.xml loads and scans entire file. Edit this file add homepage "redirect.jsp" servlet named "spring" servlet "spring" mapping with url-pattern "/"
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>redirect.jsp</welcome-file> </welcome-file-list> <display-name>Spring-Hibernate</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

We have named "spring" servlet in web.xml file, so we need to create this file and add Spring and Hibernate configurations in it. Since the name is spring, servlet name will be "spring-servlet.xml"

This xml file contains base package location(com.tutorial), MVC view resolver, DataSource definition, Hibernate session factory and Hibernate transaction manager.

Place the following credentials in datasource bean:

driverName = com.mysql.jdbc.Driver databaseurl = jdbc:mysql://localhost/tutorial username = <your database username> password = <your database password>
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="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:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 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/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.tutorial" /> <mvc:annotation-driven /> <beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <beans:property name="prefix" value="/WEB-INF/jsp/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost/tutorial" /> <beans:property name="username" value="username" /> <beans:property name="password" value="password" /> </beans:bean> <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="packagesToScan" value="com.tutorial.entity" /> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQSDialect</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="sessionFactory" /> </beans:bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans:beans>

"" in above servlet code means that the project will be annotation driven. Hibernate will search for annotations in the project.

Now under com.tutorial, create an entity package. Under this package, create Student.java class file which acts as an entity.

Student.java

package com.tutorial.entity; 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 = "student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "roll") private Integer roll; @Column(name = "name") private String name; @Column(name = "school") private String school; public Integer getRoll() { return roll; } public void setRoll(Integer roll) { this.roll = roll; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } } }

@Table denotes table with name = student
@Id denotes field with Primary Key
@Column denotes a field in the table

Now we need to create a Data Access Object named StudentDAO.java which will be placed in com.tutorial.dao package. This class will contain an interface for adding student, searching and removing student with id, viewing all students.

StudentDAO.java

package com.tutorial.dao; import com.tutorial.entity.Student; public interface StudentDAO{ public void saveStudentObj(Student obj); public List<Student> getAllStudents(); public Student getStudentObj(int id); public void removeStudentObj(int id);

To make our code modular, we will write the above method's implementation in another file StudentDAOImplementation.java.
@Repository annotation means that this file acts as the database of the application.

StudentDAOImplementation.java

package com.tutorial.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tutorial.entity.Student; @Repository public class StudentDAOImplementation implements StudentDAO { @Autowired SessionFactory sessionFactory; @Override public void saveStudentObj(Student studentObj) { sessionFactory.getCurrentSession().saveOrUpdate(studentObj); } @Override public List<Student> getAllStudents() { Session currentSession = sessionFactory.getCurrentSession(); List<Student> theQuery = currentSession.createQuery("from Student").list(); return theQuery; } @Override public Student getStudentObj(int id) { Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, id); return studentObj; } @Override public void removeStudentObj(int id) { Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, id); sessionFactory.getCurrentSession().delete(studentObj); }

Now lets create services for our WebApplication. These will be stored in com.tutorial.service package. Don't confuse between methods written in DAO and the ones in service. DAO is meant to be the database of the application, whereas service contain methods the user interacts with. Like DAO, we will create an interface first.

StudentService.java

package com.tutorial.service; import com.tutorial.entity.Student; public interface StudentService{ public void saveStudentObj(Student obj); public List<Student> getAllStudents(); public Student getStudentObj(int id); public void removeStudentObj(int id); }
Now lets write its implementation. Note that @Service annotation will be added as this is a service.
package com.tutorial.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tutorial.dao.StudentDAO; import com.tutorial.entity.Student; @Service public class StudentServiceImplementation implements StudentService { @Autowired StudentDAO studentDAO; @Override @Transactional public void saveStudentObj(Student studentObj) { studentDAO.saveStudentObj(studentObj); } @Override @Transactional public List<Student> getAllStudents() { return studentDAO.getAllStudents(); } @Override @Transactional public Student getStudentObj(int id) { return studentDAO.getStudentObj(id); } @Override @Transactional public void removeStudentObj(int id) { studentDAO.removeStudentObj(id); } }

MVC is short for Model, View and Controller. We have completed the Model part. Now lets work on Controller. Controller take care of which part of program to invoke (eg. which webpage to show on button click)
Lets create a controller named "StudentController.java" under com.tutorial.controller package.

StudentController.java

package com.tutorial.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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.tutorial.entity.Student; import com.tutorial.service.StudentService; @Controller @RequestMapping(value = "/student") public class StudentController { @Autowired StudentService studentService; @RequestMapping("/showFormForAdd") public String showAddForm(Model model) { model.addAttribute("student", new Student()); return "student-form"; } @RequestMapping("/saveProcess") public String saveStudentObj(@ModelAttribute("student") Student studentObj) { studentService.saveStudentObj(studentObj); return "redirect:/student/list"; } @RequestMapping("/list") public String listOfStudents(Model model) { model.addAttribute("studentsList", studentService.getAllStudents()); return "list-students"; } @RequestMapping("/displayUpdateForm") public String showUpdateForm(@RequestParam("studentId") int theId, Model model) { model.addAttribute("student", studentService.getStudentObj(theId)); return "student-form"; } @RequestMapping("/displayDeleteForm") public String deleteStudentObj(@RequestParam("studentId") int theId, Model model) { studentService.removeStudentObj(theId); return "redirect:/student/list"; } }

@RequestMapping maps the request with the redirecting page.

With this we have completed the controller part too. Now we have to write View of the application to complete MVC architecture. View is nothing but the set of webpages with JSPs. We will create all the jsp files in the jsps folder inside WEB-INF.

list-students.jsp will view all the students and their details present in the database.

list-students.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://www.springframework.org/tags" prefix="spring"%> <%@ 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"> </head> <body> <h1 align="center">All Students</h1> <button onclick="window.location.href = 'showFormForAdd'; return false;">Add Student</button> <hr /> <center> <table border="1"> <tr> <th>Roll no.</th> <th>Name</th> <th>School</th> </tr> <c:forEach items="${studentsList}" var="s"> <c:url var="updateLink" value="/student/displayUpdateForm.html"> <c:param name="studentId" value="${s.id}" /> </c:url> <c:url var="deleteLink" value="/student/displayDeleteForm.html"> <c:param name="studentId" value="${s.id}" /> </c:url> <tr> <td>${s.roll}</td> <td>${s.name}</td> <td>${s.school}</td> <td><a href="${updateLink}">Update</a> | <a href="${deleteLink}" onclick="if(!(confirm('Are you sure ?'))) return false">Delete</a></td> </tr> </c:forEach> </table> </center> </body> </html>
To add new student, we need to make a form in which the user can insert data.

displayUpdateForm.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://www.springframework.org/tags" prefix="spring"%> <%@ 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>New Student</title> </head> <body> <h1>Enter New Student's information</h1> <hr /> <form:form action="saveProcess.html" modelAttribute="student"> <table> <form:hidden path="id" /> <form:hidden path="" value="${student.hobbies}" id="hobbies" /> <tr> <td><b>Roll No. </b></td> <td><form:input path="roll" /></td> </tr> <tr> <td><b>Full Name:</b></td> <td><form:input path="name" /></td> </tr> <tr> <td><b>School:</b></td> <td><form:input path="school" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Save" /> <input type="reset" value="Reset" /></td> </tr> </table> </form:form> <hr /> <a href="list">Home</a> </body> </html>
When our application loads, redirect.jsp loads. But we want list.jsp to be the first page. So edit the redirect.jsp so that it redirects to list page.
<% response.sendRedirect("student/list"); %>

Output

  1. List Page
    Output in Spring Project CRUD operations Tutorial with Hibernate and mysql
  2. Update information page
    Update page in Spring Project CRUD operations Tutorial with Hibernate and mysql

Solution Worked 1 UpvotesUpvote

        

Solution Didn't Worked 2 DownvotesDownvote



Comments



Search


Search Tags