CRUD trong ứng dụng Spring Web MVC với Hibernate-SQL Server Database
Đăng lúc: 10:44 PM - 27/10/2023 bởi Charles Chung - 2860Trong bài viết này tôi sẽ hướng dẫn thực hiện các thao tác CRUD trong ứng dụng Spring Web MVC với Hibernate và cơ sở dữ liệu SQL Server

1. Kiến thức cần có
- Căn bản về SQL Server database, cách cài đặt cơ sở dữ liệu SQL Server, công cụng Microsoft SQL Server Management Studio, xem chi tiết ở đây
- Lập trình Java Core
- HTML - CSS - JavaScript
- JSP và Servlet
2. Các bước tạo ứng dụng Spring Hibernate và thực hiện các thao tác CRUD
Bước 1: Tạo bảng và nhập dữ liệu
- Mở Microsoft SQL Server Management Studio tạo bảng như hình dưới
Bước 2: Tạo Dynamic Web Project (xem chi tiết ở bài trước nhé)
- Khởi động Eclispe IDE -> vào menu File -> New -> Dynamic Web Project -> Đặt tên "CRUDSpringHibernateSQLServer"
Tiếp tục kích vào Next -> Next -> Chọn Generate web.xml deyployment desciptor -> kích finish
Bước 3: Convert sang Maven Project
- Kích chuột phải vào Project vừa tạo -> Configure -> Convert to Maven Project -> Finish
Bước 4: Khai báo các Maven Dependencies cần thiết
- Mở file pom.xml và cấu hình các Maven Dependencies gồm: spring web, web mvc, spring-orm, hibernate, servlet api, jstl. Cấu hình xem chi tiết ở bài trước nhé nhưng bỏ dependency oracle đi
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.26.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>12.3.0.jre17-preview</version>
</dependency>
- Nếu bạn không sử dụng dependency của mssql trong file pom.xml thì tải tệp sqljdbc4.2.jar về và copy paste vào thư mục WEB-INF/lib -> tiếp theo kích chuột phải vào Project -> Buid Path -> Configure Buid Path -> Add file sqljdbc4.2.jar vào đường dẫn như hình
Bước 5: Cấu hình ứng dụng Spring Web Mvc
- Trong thư mục WEB-INF tạo thư mục views và tệp tin spring-servlet.xml như hình dưới
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- chỉ ra các package chứa các lớp java được đăng ký như là các bean -->
<context:component-scan
base-package="controllers,dao" />
<!-- chỉ tìm kiếm các bean trong cùng context application mà nó được định nghĩa -->
<context:annotation-config />
<!-- mặc định các basic components được ủy quyền gửi request tới các controller -->
<mvc:annotation-driven />
<!-- cấu hình bean xác định view sẽ được sinh ra (thư mục chứa các view, đuôi tệp tin view) -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
<!-- Tạo đối tượng bean dataSource kết nối database oracle -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=bkap;Encrypt=True;trustServerCertificate=True;"></property>
<property name="username" value="sa"></property>
<property name="password" value="123465"></property>
</bean>
<!-- Tạo đối tượng bean sessionFactory cấu hình Hibernate -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="entities"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
</bean>
</beans>
- Mở tệp web.xml và cấu hình vào bên trong thẻ <web-app> như sau:
<!-- Cấu hình UTF-8 khi request hoặc response -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Cấu hình Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Bước 6: Tạo các tệp tin theo cấu trúc mô tả sau (xem chi tiết ở bài trước nhé)
- Tạo gói entities với lớp Student
package entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "students")
public class Student implements Serializable {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY) //mã tự động tăng
// private int studentId;
@Id
private String studentId;
private String fullName;
private boolean gender;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date birthDay;
private String email;
private String phone;
private String address;
private boolean active;
public Student() {
// TODO Auto-generated constructor stub
}
public String getStudentId() {
return studentId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
}
- Tạo gói dao với lớp StudentDAO
package dao;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import entities.Student;
@Repository
public class StudentDAO {
@Autowired
SessionFactory sessionFactory;
public StudentDAO() {
}
// Lấy tất cả sinh viên
public List<Student> getAll() {
Session session = sessionFactory.openSession();
List result = session.createQuery("from Student").getResultList();
return result;
}
// Tìm kiếm theo tên
public List<Student> search(String name) {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Student where fullName like :name");
query.setParameter("name", "%" + name + "%");
return query.getResultList();
}
// Insert sinh viên vào database
public void insert(Student student) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
}
// Update lại thông tin sinh viên
public void update(Student student) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.update(student);
session.getTransaction().commit();
}
// Xóa sinh viên
public void delete(String id) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
var st = session.get(Student.class, id);
session.remove(st);
session.getTransaction().commit();
}
// Lấy sinh viên theo id
public Student getById(String id) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Student st = session.get(Student.class, id);
session.getTransaction().commit();
return st;
}
}
- Tạo gói controllers với lớp StudentController
package controllers;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import dao.StudentDAO;
import entities.Student;
@Controller
public class StudentController {
@Autowired
StudentDAO studentDAO;
@RequestMapping(value= {"/","students"},method = RequestMethod.GET)
public String index(Model model) {
model.addAttribute("students",studentDAO.getAll());
return "index";
}
@RequestMapping(value= "addstudent",method = RequestMethod.GET)
public String create(Model model) {
var student=new Student();
model.addAttribute("student",student);
return "create";
}
@RequestMapping(value= "save",method = RequestMethod.POST)
public String save(@ModelAttribute("student") Student student, Model model) {
try {
studentDAO.insert(student);
}catch(Exception ex) {
model.addAttribute("error",ex.getMessage());
model.addAttribute("student",student);
return "create";
}
return "redirect:/students";
}
@RequestMapping(value= "edit",method = RequestMethod.GET)
public String edit(@RequestParam("id") String id,Model model) {
var student=studentDAO.getById(id);
model.addAttribute("student",student);
return "edit";
}
@RequestMapping(value= "update",method = RequestMethod.POST)
public String update(@ModelAttribute("student") Student student, Model model) {
try {
studentDAO.update(student);
}catch(Exception ex) {
model.addAttribute("error",ex.getMessage());
model.addAttribute("student",student);
return "edit";
}
return "redirect:/students";
}
@RequestMapping(value= "search",method = RequestMethod.POST)
public String update(String searchname, Model model) {
model.addAttribute("students",studentDAO.search(searchname));
return "index";
}
@RequestMapping(value= "delete",method = RequestMethod.GET)
public String delete(@RequestParam("id") String id) {
studentDAO.delete(id);
return "redirect:/students";
}
}
- Tạo thư mục views trong WEB-INF với các tệp index.jsp, create.jsp, edit.jsp
- Tệp index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CRUD Spring Hibernate with Oracle Database</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<h1>DANH SÁCH SINH VIÊN</h1>
<form action="search" method="post">
Nhập tên cần tìm <input type="text" name="searchname"/> <button class="btn btn-info"> Tìm </button> <a class="btn btn-primary" href="addstudent">Thêm mới</a>
</form><hr />
<table class="table table-bordered">
<tr>
<th>Mã SV</th>
<th>Họ và tên</th>
<th>Ngày sinh</th>
<th>Giới tính</th>
<th>Email</th>
<th>Điện thoại</th>
<th>Địa chỉ</th>
<th>Tình trạng</th>
<th></th>
</tr>
<c:forEach var="s" items="${students}">
<tr>
<td>${s.studentId}</td>
<td>${s.fullName}</td>
<td>${s.birthDay}</td>
<td>
<c:choose>
<c:when test="${s.gender==true}">Nam</c:when>
<c:otherwise>Nữ</c:otherwise>
</c:choose>
</td>
<td>${s.email}</td>
<td>${s.phone}</td>
<td>${s.address}</td>
<td>
<c:choose>
<c:when test="${s.active==true}">Đang học</c:when>
<c:otherwise>Dừng</c:otherwise>
</c:choose>
</td>
<td>
<a onclick="return confirm('Bạn có muốn xóa không?')" class="btn btn-danger" href="delete?id=${s.studentId}">Xóa</a>
<a class="btn btn-success" href="edit?id=${s.studentId}">Sửa</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
- Tệp create.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thêm mới sinh viên</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Thêm mới sinh viên</h1>
<span style="color: red">${error}</span>
<f:form action="save" method="post" modelAttribute="student">
<table class="table">
<tr>
<td>Mã số</td>
<td><f:input path="studentId" /></td>
</tr>
<tr>
<td>Họ và tên</td>
<td><f:input path="fullName" /></td>
</tr>
<tr>
<td>Ngày sinh</td>
<td><f:input path="birthDay"/></td>
</tr>
<tr>
<td>Giới tính</td>
<td>
<select name="gender" id="gender">
<option value="1">Nam</option>
<option value="0">Nữ</option>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><f:input path="email" /></td>
</tr>
<tr>
<td>Điện thoại</td>
<td><f:input path="phone" /></td>
</tr>
<tr>
<td>Địa chỉ</td>
<td><f:input path="address" /></td>
</tr>
<tr>
<td>Tình trạng</td>
<td>
<select name="active" id="active">
<option value="1">Đang học</option>
<option value="0">Dừng</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<button class="btn btn-primary">Lưu</button>
</td>
</tr>
</table>
</f:form>
</div>
</body>
</html>
- Tệp edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sửa sinh viên</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Sửa sinh viên</h1>
<f:form action="update" method="post" modelAttribute="student">
<table class="table">
<tr>
<td>Mã số</td>
<td><f:hidden path="studentId"/>${student.studentId}</td>
</tr>
<tr>
<td>Họ và tên</td>
<td><f:input path="fullName"/></td>
</tr>
<tr>
<td>Ngày sinh</td>
<td><f:input path="birthDay"/></td>
</tr>
<tr>
<td>Giới tính</td>
<td>
<select name="gender" id="gender">
<c:if test="${student.gender==true}">
<option selected value="1">Nam</option>
<option value="0">Nữ</option>
</c:if>
<c:if test="${student.gender==false}">
<option value="1">Nam</option>
<option selected value="0">Nữ</option>
</c:if>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><f:input path="email"/></td>
</tr>
<tr>
<td>Điện thoại</td>
<td><f:input path="phone"/></td>
</tr>
<tr>
<td>Địa chỉ</td>
<td><f:input path="address"/></td>
</tr>
<tr>
<td>Tình trạng</td>
<td>
<select name="active" id="active">
<c:if test="${student.active==true}">
<option selected value="1">Đang học</option>
<option value="0">Dừng</option>
</c:if>
<c:if test="${student.active==false}">
<option value="1">Đang học</option>
<option selected value="0">Dừng</option>
</c:if>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<button class="btn btn-primary"> Cập nhật </button>
</td>
</tr>
</table>
</f:form>
</div>
</body>
</html>
Bước 7: Run application
- Kích chuột phải vào project chọn Run As -> Run on Server -> Tomcat v9.0
Kích để tải source code bài CRUD trong ứng dụng Spring Web MVC với Hibernate-SQL Server Database
Training online liên hệ: Charles Chung
Video
thay lời cảm ơn!
Các bài cũ hơn
- Hibernate One to Many Mapping trong Spring Web MVC và cơ sở dữ liệu Oracle (08:01 PM - 26/10/2023)
- CRUD trong ứng dụng Spring Web MVC với Hibernate-Oracle Database (11:02 AM - 25/10/2023)
- Các cách gửi nhận dữ liệu trong Spring MVC (11:27 AM - 24/10/2023)
- Tạo và cấu hình ứng dụng Spring Web Mvc với Maven Dependencies sử dụng Eclipse IDE (09:27 PM - 22/10/2023)
- Một số Maven Dependencies dùng trong các dự án Java (09:56 AM - 18/10/2023)