Lập trình Spring Boot CRUD đơn giản MyEmployee

Sharing now

4.3/5 - (15 bình chọn)

Lập trình Spring Boot CRUD đơn giản MyEmployee

springcrud_9
Hướng dẫn lập trình Spring Boot CRUD (thêm, đọc, xóa, sửa) cơ bản. Project MyEmployee này sẽ hướng dẫn làm trang web trên nền Spring Framework chỉ có các tính năng đọc thêm xóa sửa các nhân viên đơn giản. Đây là dự án kết hợp Spring Boot + Spring MVC + Spring Data Hibernate + Thymeleaf Template engine
Yêu cầu công cụ(hoặc công cụ lập trình khác tương tự): 
Elipse + Plugin spring suite tool
Java + Tomcat
MySql 5.6
Các bước lập trình Spring Boot CRUD làm như sau ( để chi tiết hơn hãy xem video cuối bài )

Tạo Cơ sở dữ liệu

Ở đây mình sẽ tạo database là myemployee có 1 bảng employee. Trong bảng này sẽ có 3 cột: id, name, phone. Đoạn code tạo bảng:

create table employee(
        id int(10) not null auto_increment PRIMARY key,
        name nvarchar(100) not null,
        phone varchar(13) null
)

springcrud (4)

Tạo project spring boot mới:

File -> New -> Spring Starter Project
Nhập Group và Artifact tùy ý bạn. Ở đây mình nhập: Group là com.example, Package là com.example.demo và Artifact là MyEmployee
springcrud (1)
Nhấn Next, bây giờ ta sẽ thêm các thư viện: nhập “web” để tìm thêm thư viện Spring boot trên web. Tương tự nhập: “JPA”, “MySQL”, “Thymeleaf” để thêm chúng vào project.
springcrud (2)
Nhấn Finish
Project sẽ được build.  Sau khi tạo project xong sẽ có cây thư mục như hình.
springcrud (3)

Thêm thư viện pom.xml

Trong dự án này, mình sử dụng Bootstrap 3.3.7 và jQuery 1.12.4 nên chúng ta sẽ thêm vào pom.xml như sau:

Lúc này file pom.xml sẽ có nội dung thế này, bao gồm đã thêm thư viện Bootstrap và jquery (phần hightlight)

Thiết lập project spring boot + hibernate + thymeleaf

Thiết lập file application.properties với hibernate và thymeleaf như sau:

# ===============================
# THYMELEAF
# ===============================
spring.thymeleaf.cache=false
# ===============================
# DATASOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database
spring.datasource.url=jdbc:mysql://localhost:3306/myemployee?useSSL=false
# MySQL username and password
spring.datasource.username=root
spring.datasource.password=root
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.validation-query=SELECT 1
# ===============================
# JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Chúng ta cần lưu ý đoạn code kết nối tới cơ sở dữ liệu này. Bao gồm database và user, password kết nối tới mysql server

# Connection url for the database
spring.datasource.url=jdbc:mysql://localhost:3306/myemployee?useSSL=false
# MySQL username and password
spring.datasource.username=root
spring.datasource.password=root

Tạo các class java cho project Spring Boot CRUD

Bắt tay vào tạo class thôi! Do project Spring Boot CRUD chúng ta làm theo mô hình Spring MVC nên cần có các phần (package):

  • Model
  • Repository
  • Service
  • Controller

Đầu tiên chúng ta tạo class Employee.java trong package com.example.demo.model
springcrud (5)
Nội dung tương ứng với bảng đã tạo bên cơ sở dữ liệu như sau:

package com.example.demo.model;
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 = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name = "id", nullable = false)
	private long id;
	@Column(name = "name", nullable = false)
	private String name;
	@Column(name = "phone")
	private String phone;
	public Employee() {
		super();
	}
	public Employee(long id, String name, String phone) {
		super();
		this.id = id;
		this.name = name;
		this.phone = phone;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}

Tiếp theo chúng ta tạo class EmployeeRepository.java trong package com.example.demo.repository
Nội dung EmployeeRepository.java được extends JpaRepository như sau:

package com.example.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findByNameContaining(String q);
}

Tiếp đến chúng ta tạo interface EmployeeService.java và class EmployeeServiceImpl.java implements từ interface EmployeeService.java trong package com.example.demo.service 
interface EmployeeService.java

package com.example.demo.service;
import java.util.List;
import com.example.demo.model.Employee;
public interface EmployeeService {
	Iterable<Employee> findAll();
    List<Employee> search(String q);
    Employee findOne(long id);
    void save(Employee emp);
    void delete(Employee emp);
}

class EmployeeServiceImpl.java

package com.example.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
@Service
public class EmployeeServiceImpl implements EmployeeService {
	@Autowired
    private EmployeeRepository employeeRepository;
    @Override
    public Iterable<Employee> findAll() {
        return employeeRepository.findAll();
    }
    @Override
    public List<Employee> search(String q) {
        return employeeRepository.findByNameContaining(q);
    }
    @Override
    public Employee findOne(long id) {
        return employeeRepository.findOne(id);
    }
    @Override
    public void save(Employee emp) {
    	employeeRepository.save(emp);
    }
    @Override
    public void delete(Employee emp) {
    	employeeRepository.delete(emp);
    }
}

Cuối cùng chúng ta tạo class EmployeeController.java trong package com.example.demo.controller

package com.example.demo.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
@Controller
public class EmployeeController {
	@Autowired
	private EmployeeService employeeService;
	@GetMapping("/employee")
	public String index(Model model) {
		model.addAttribute("employees", employeeService.findAll());
		return "list";
	}
	@GetMapping("/employee/create")
	public String create(Model model) {
		model.addAttribute("employee", new Employee());
		return "form";
	}
	@GetMapping("/employee/{id}/edit")
	public String edit(@PathVariable int id, Model model) {
		model.addAttribute("employee", employeeService.findOne(id));
		return "form";
	}
	@PostMapping("/employee/save")
	public String save(@Valid Employee employee, BindingResult result, RedirectAttributes redirect) {
		if (result.hasErrors()) {
			return "form";
		}
		employeeService.save(employee);
		redirect.addFlashAttribute("success", "Saved employee successfully!");
		return "redirect:/employee";
	}
	@GetMapping("/employee/{id}/delete")
	public String delete(@PathVariable int id, RedirectAttributes redirect) {
		Employee emp = employeeService.findOne(id);
                employeeService.delete(emp);
		redirect.addFlashAttribute("success", "Deleted employee successfully!");
		return "redirect:/employee";
	}
	@GetMapping("/employee/search")
	public String search(@RequestParam("s") String s, Model model) {
		if (s.equals("")) {
			return "redirect:/employee";
		}
		model.addAttribute("employees", employeeService.search(s));
		return "list";
	}
}

Sau khi xong chúng ta sẽ được cấu trúc thư mục như thế này
springcrud (6)

Tạo giao diện View dùng thymeleaf template

Phần xử lý đã xong bây giờ chúng ta sẽ viết phần view. Các bạn thêm thư mục và các file html như hình trong thư mục src/main/resources
springcrud (7)
Chúng ta cần các trang: hiện danh sách nhân viên, trang thêm/sửa nhân viên. Ở đây chúng ta sẽ viết 3 file html chính: layout.html, form.html, list.html. Đồng thời thêm css cho giao diện trang web đẹp chút 🙂 là file style.css trong thư mục static/css
Để tối ưu code giao diện view mình sẽ dùng fragment của thymeleaf  nên chúng ta sẽ viết các phần như head, header và footer chung cho tất cả các trang và bỏ vào file layout.html
Nội dung layout.html

Mình giải thích chút về đoạn code trên (1 phần thôi còn lại tương tự nhé)

<link href="../static/css/style.css"
      th:href="@{css/style.css}" rel="stylesheet" />
  • Thuộc tính href là của HTML5, cung cấp đường dẫn tới file style.css cho trình duyệt nếu như server chưa run.
  • Thuộc tính th:href là của Thymeleaf, cung cấp đường dẫn tới file style.css cho trình duyệt khi server run. @{} mà một biểu thức SPeL xác định đường dẫn.


Do bootstrap và jquery mình dùng file jar (nằm trong maven dependencies của project) nên sẽ có đường dẫn như sau /webjars/<tên thư viện>/<phiên bản>
Trang list.html sẽ là trang chủ và hiện danh sách nhân viên. Đồng thời hiện thông báo khi thêm/sửa/xóa nhân viên.
Nội dung list.html

Mình giải thích chút (1 phần thôi còn lại tương tự nhé)

<footer th:replace="layout :: footer"></footer>
  • layout là tham chiếu tới file layout.html
  • head, headerfooter sau :: là các fragment selector, chính là giá trị của thuộc tính th:fragment của các thẻ head, navfooter ở file layout.html
  • Thuộc tính th:each tương ứng với “câu lệnh foreach”
  • Thuộc tính th:text dùng để đổ dữ liệu dưới dạng text vào thẻ HTML
  • ${contacts} là một iterated variable, chính là đối tượng contacts truyền từ Controller
  • contact là một iteration variable
  • iterStat là một status variable giúp chúng ta theo dõi vòng lặp, biến count sẽ lấy ra chỉ số hiện tại của vòng lặp (bắt đầu từ 1)

Trang form.html sẽ hiện form thêm/sửa nhân viên.
Nội dung form.html

Mình giải thích chút (1 phần thôi còn lại tương tự nhé)
Mỗi thuộc tính của employee sẽ tương ứng với một input trong form. Nên mình sẽ thêm thuộc tính th:field=*{fieldName} vào các input. Do khi submit form, chúng ta cần phải chỉ cho Hibernate biết entity nào được ánh xạ qua(mapping), ví dụ <input type="hidden" th:field="*{id}" /> để chỉ ra ID của entity Employee.
Nội dung style.css

.main-content {
	min-height: 500px;
	max-width: 700px;
	margin-top: 70px;
}
.list {
	max-width: 800px;
}
.form {
	max-width: 450px;
}
.row {
	margin-top: 30px;
}
.table th, td {
   text-align: center;
}
.field-error {
	border: 1px solid #ff0000;
	margin-bottom: 10px;
}

Xong. Mọi thứ đã ổn chạy chương trình thôi nào ! Nhấn phải project chọn Run as -> Spring Boot App. Vào trình duyệt web gõ: localhost:8080/employee (hoặc cổng port của bạn). “/employee” do bạn đã thiết lập trong controller.
springcrud (8)

Kết quả: Lập trình Spring Boot CRUD đơn giản MyEmployee

springcrud_9

Download source code update 2019

Video hướng dẫn chi tiết Lập trình Spring Boot CRUD đơn giản MyEmployee(video code cũ chỉ work trên mysql 5.6)


Đọc thêm: Hướng dẫn phân trang trong Thymeleaf và Spring Boot


Sharing now

12 bình luận về “Lập trình Spring Boot CRUD đơn giản MyEmployee”

  1. anh cho emhỏi giả sử em làm file employeeDAO như trong spring mvc chứ không làm file EmployeeRepository thì sự khác nhau giữa chúng là như thế nào ? có j sai mong bỏ qua do e chưa hiểu rõ bản chất

    Trả lời
  2. AD cho e hỏi mình làm đến bước taọ 1 đối tượng mới nhưng khi mình nhập đầy đủ thông tin, ấn save thì eclipse báo lỗi EL1008E: Property or field ‘…’ cannot be found on object of type ‘com.example.demo.model…’ – maybe not public or not valid?
    Nhưng ở trong CSDL của mình vẫn insert được đối tượng vừa nhập vào bảng. báo lỗi ở phần líst.html mấy dòng 48,49 ý ạ. Nó báo cái trường đó ( ví dụ là name) cannot be found….
    Ad có thể giải đáp dùm e được không ạ. Em cảm ơn!

    Trả lời
  3. ad làm thêm 1 demo crud với 2 bảng trở lên có quan hệ với nhau đi ạ. em làm theo giống ad mà chỉ chạy dc với database có 1 bảng, chứ em bổ xung thêm 1 bảng có quan hệ với nhau nó báo Unknow column ‘lop0_.ma_lop’ in ‘field list’ hoài

    Trả lời

Viết một bình luận