Spring Boot H2 简明教程
Spring Boot & H2 - Update Record
让我们现在更新到目前为止创建的项目以准备一个完整的更新记录API并对其进行测试。
Update Controller
// Use service.saveOrUpdate() to update an employee record
@PutMapping("/employee")
public void updateEmployee(@RequestBody Employee employee) {
employeeService.saveOrUpdate(employee);
}
EmployeeController
package com.tutorialspoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;
@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@GetMapping("/employees")
public List<Employee> getAllEmployees(){
return employeeService.getAllEmployees();
}
@GetMapping("/employee/{id}")
public Employee getEmployee(@PathVariable("id") int id) {
return employeeService.getEmployeeById(id);
}
@DeleteMapping("/employee/{id}")
public void deleteEmployee(@PathVariable("id") int id) {
employeeService.deleteEmployeeById(id);
}
@PostMapping("/employee")
public void addEmployee(@RequestBody Employee employee) {
employeeService.saveOrUpdate(employee);
}
@PutMapping("/employee")
public void updateEmployee(@RequestBody Employee employee) {
employeeService.saveOrUpdate(employee);
}
}
Run the application
在 Eclipse 中,按照在 Application Setup 准备期间准备 Employee Application 配置。
Eclipse 控制台将显示类似的输出。
[INFO] Scanning for projects...
...
2021-07-24 20:51:14.823 INFO 9760 --- [ restartedMain] c.t.s.SprintBootH2Application
: Started SprintBootH2Application in 7.353 seconds (JVM running for 8.397)
服务器启动并运行后,使用 Postman 先执行 POST 请求以添加记录。
在 POSTMAN 中设置以下参数。
-
HTTP Method − POST
-
正文 - An employee JSON
{
"id": "1",
"age": "35",
"name": "Julie",
"email": "julie@gmail.com"
}
单击发送按钮并检查响应状态是否为OK。
现在发出Put请求来更新该记录。
在 POSTMAN 中设置以下参数。
-
HTTP Method − PUT
-
正文 - An employee JSON
{
"id": "1",
"age": "35",
"name": "Julie",
"email": "julie.roberts@gmail.com"
}
单击发送按钮并验证响应状态是否为OK。
现在发出GET请求来获取所有记录。
在 POSTMAN 中设置以下参数。
-
HTTP Method − GET
单击发送按钮并验证响应。
[{
"id": "1",
"age": "35",
"name": "Julie",
"email": "julie.roberts@gmail.com"
}]