Spring Boot, Spring Data JPA, Spring Rest API CRUD
Spring Boot, Spring Data JPA, Spring Rest API CRUD
- Giới thiệu
- Cài đặt
- Chạy thử
# Giới thiệu
Trong hướng dẫn này, mình sẽ xây dựng một ví dụ API Spring Boot Rest CRUD với Maven sử dụng Spring Data JPA để tương tác với cơ sở dữ liệu MySQLĐây là những api trong ví dụ này
Methods | Urls | Actions |
---|---|---|
POST | /api/employee | Tạo mới employee |
GET | /api/employee | Lấy tất cả employee |
GET | /api/employee/:id | Lấy employee bằng id |
DELETE | /api/employee/:id | Xoá employee bằng id |
PUT | /api/employee/:id | Cập nhật employee bằng id |
# Cài đặt
Tạo database trong cơ sở dữ liệu MySQL
DROP DATABASE IF EXISTS employeedb; CREATE DATABASE employeedb; USE employeedb; CREATE TABLE employee( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), salary float ); INSERT INTO employee VALUES (1, 'Pham Quang Huy', 50.3); INSERT INTO employee VALUES (2, 'Pham Xuan Hoai', 80.7);
Cấu trúc source Spring Boot
EmployeeController.java: nhận request, xử lý và trả về dữ liệu
MessageController.java: hỗ trợ tuỳ biến thông điệp trả về
Employee.java: là entity mapping với database
IEmployeeRepository: là repository kế thừa JpaRepository
EmployeeService: là service implement IEmployeeRepository
application.properties: cấu hình hệ thống chính
Đầu tiên, trong pom.xml thêm các dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
application.properties:
# Connect MySQL spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/employeedb spring.datasource.username=root spring.datasource.password=root # Hibernate spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Trong thư mục entity tạo Employee.java ở đây mình generate từ database các bạn có thể tham khảo Spring Boot generate entity class from MySQL Database using IntelliJ IDEA ULTIMATE
package com.fpt.employeemanagementapi.entities; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Objects; @Entity public class Employee { private int id; private String name; private Double salary; private Integer gender; private Boolean status; public Employee() { } public Employee(int id, String name, Double salary, Integer gender, Boolean status) { this.id = id; this.name = name; this.salary = salary; this.gender = gender; this.status = status; } @Id @Column(name = "id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "salary") public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Basic @Column(name = "gender") public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } @Basic @Column(name = "status") public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id && Objects.equals(name, employee.name) && Objects.equals(salary, employee.salary) && Objects.equals(gender, employee.gender) && Objects.equals(status, employee.status); } @Override public int hashCode() { return Objects.hash(id, name, salary, gender, status); } }
dto/Message.java
package com.fpt.demojavadocfast.dto; public class Message { String msg; public Message() { } public Message(String msg) { this.msg = msg; } public String getMess() { return msg; } public void setMess(String msg) { this.msg = msg; } }
repository/EmployeeRepository.java
package com.fpt.demojavadocfast.repository; import com.fpt.demojavadocfast.entity.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface IEmployeeRepository extends JpaRepository<Employee, Integer> {}
service/EmployeeService.java
package com.fpt.demojavadocfast.service;
import com.fpt.demojavadocfast.entity.Employee;
import com.fpt.demojavadocfast.repository.IEmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
@Autowired
IEmployeeRepository iEmployeeRepository;
public List<Employee> findAll(){
return iEmployeeRepository.findAll();
}
public Employee findEmployeeById(int id){
return iEmployeeRepository.findById(id).get();
}
public boolean existById(int id){
return iEmployeeRepository.existsById(id);
}
public void save(Employee employee){
iEmployeeRepository.save(employee);
}
public void deleteById(int id){
iEmployeeRepository.deleteById(id);
}
}
controller/EmployeeController.java
Trên class EmployeeController thêm annotaion @CrossOrigin để thông báo cho browser biết domain nào được truy xuất tài nguyên từ server, thiết lập giá trị * để chấp nhận request từ tất cả domain
package com.fpt.demojavadocfast.controller; import com.fpt.demojavadocfast.dto.Message; import com.fpt.demojavadocfast.entity.Employee; import com.fpt.demojavadocfast.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @CrossOrigin("*") @RequestMapping("/api") public class EmployeeController { @Autowired EmployeeService employeeService; @GetMapping("/employee") public ResponseEntity<List<Employee>> getAllEmployee(){ try { List<Employee> employees = employeeService.findAll(); return new ResponseEntity(employees, HttpStatus.OK); }catch (Exception e){ return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/employee/{id}") public ResponseEntity<?> getEmployee(@PathVariable("id") int id){ try { if (employeeService.existById(id)){ Employee employee = employeeService.findEmployeeById(id); return new ResponseEntity(employee, HttpStatus.OK); } return new ResponseEntity(new Message("Employee not exist!!!"), HttpStatus.BAD_REQUEST); }catch (Exception e){ return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping("/employee/{id}") public ResponseEntity<?> deleteEmployee(@PathVariable("id") int id){ try { if (employeeService.existById(id)){ Employee employee = employeeService.findEmployeeById(id); employeeService.deleteById(id); return new ResponseEntity(employee, HttpStatus.OK); } return new ResponseEntity(new Message("Employee not exist!!!"), HttpStatus.BAD_REQUEST); }catch (Exception e){ return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping("/employee") public ResponseEntity<?> addEmployee(@RequestBody Employee employee){ try { if (!employeeService.existById(employee.getId())){ Employee employeeNew = new Employee(employee.getId(), employee.getName(), employee.getSalary()); employeeService.save(employeeNew); return new ResponseEntity(employee, HttpStatus.OK); } return new ResponseEntity(new Message("Employee id is existed!!!"), HttpStatus.BAD_REQUEST); }catch (Exception e){ return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping("/employee") public ResponseEntity<?> updateEmployee(@RequestBody Employee employee){ try { if (employeeService.existById(employee.getId())){ Employee employeeUpdate = employeeService.findEmployeeById(employee.getId()); employeeUpdate.setName(employee.getName()); employeeUpdate.setSalary(employee.getSalary()); employeeService.save(employeeUpdate); return new ResponseEntity(employee, HttpStatus.OK); } return new ResponseEntity(new Message("Employee not exist!!!"), HttpStatus.BAD_REQUEST); }catch (Exception e){ return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } }
# Chạy thử
Mình sử dụng Postman để test API:
Lấy tất cả employee
Thêm employee mới
Dữ liệu trước khi thêm vào
Thêm dữ liệu trong Postman
Trường hợp trùng id
Cập nhật employee không tồn tại
Xoá employee bằng id
Dự liệu sau khi xoá
xoá employee không tồn tại
Cảm ơn các bạn đã ghé thăm blog!
Nhận xét
Đăng nhận xét