第七节:更新数据 -- update
和其它框架一样,在数据更新中,SpringMVC
调用的方法同Create
,即均为save()
方法。则按照前面章节的思想,我们不难写出如下数据更新的代码。
// @PutMapping 表明该方法只接收 put 请求.
@PutMapping("/{id}")
public Teacher updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
// 对实体ID赋值, 并执行更新操作
teacher.setId(id);
return teacherRepository.save(teacher);
}
这里,我们使用了put
方法,其实和get
,post
一样,这仅仅是一个请求的方法而已。除了get
,post
,put
方法外,我们还会接触到patch
及delete
方法。
我们简单做个汇总:
方法名 | 描述 |
---|---|
get | 用于数据的查询操作 |
post | 用于数据的新增操作 |
put | 用于数据的更新操作(更新实体的全部字段) |
patch | 用于数据的更新操作(更新实体的部分字段) |
delete | 用于数据的删除操作 |
测试
和read
操作相同,我们在进行数据的更新前,需要先新增一个实体。然后再对这个实体进行修改。
完善代码
我们看到,我们新增了一个教师,然后进行查询得到了这个教师的数据,再进行修改,然后再查询,发现教师的数据的确被我们修改了。
不过,如果我们测试充分的话,也会很容易的发现:在数据修改的过程中,如果并不存在我们要修改的数据,那么则会自动的新增一条记录。而这,并不是我们想看到的。我们想要的结果是,如果有这条记录,则更新,如果没有,则提示我们不存在该条记录。
完善代码如下:
// @PutMapping 表明该方法只接收 put 请求.
@PutMapping("/{id}")
public Teacher updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) throws EntityNotFoundException {
// 判断是否存在该实体,如果不存在,则报错
if (teacherRepository.findOne(id) == null) {
throw new EntityNotFoundException("传入的ID值:" + id.toString() + "有误。未找到对应的实体");
}
// 对实体ID赋值, 并执行更新操作
teacher.setId(id);
return teacherRepository.save(teacher);
}
- 增加了传入
id
是否对应实体的判断, 如果没有找到,则抛出一个javax.persistence.EntityNotFoundException
异常。同时,。 - 在函数定义时,增加了
throws EntityNotFoundException
来声明抛出的异常类型。该异常能够被SpringMVC
捕获,并且转化为json
格式的报错信息进行输出
我们输入一个并不存在实体id
并进行测试,将得到如下提示信息:
除此以外,根据具体的实际情况,我们还可以使用SpringMVC
为我们准备好的其它异常类型,比如BindException
,ConversionNotSupportedException
等等。
完整代码如下:
package com.mengyunzhi.controller;
import com.mengyunzhi.repository.Teacher;
import com.mengyunzhi.repository.TeacherRepository;
import com.mengyunzhi.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;
/**
* Created by panjie on 17/4/6.
*/
// 声明为Rest控制器(支持前后台分离)
@RestController
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherRepository teacherRepository;
@Autowired
private TeacherService teacherService;
// 设置路由
@PostMapping("/save")
// 使用@RequestBody注解,将请求的`json`数据,直接加载至teacher对象
public Teacher saveTeacher(@Valid @RequestBody Teacher teacher) {
// 打印加载的数据
System.out.println(teacher);
// 调用保存操作
return teacherRepository.save(teacher);
}
// @GetMapping 表明该方法只接收 get 请求.
// {id}即为url中传入教师关键字
@GetMapping("/{id}")
// @PathVariable 获取路由中的id值
public Teacher getTeacherById(@PathVariable Long id) {
return teacherRepository.findOne(id);
}
// @PutMapping 表明该方法只接收 put 请求.
@PutMapping("/{id}")
public Teacher updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) throws EntityNotFoundException {
// 判断是否存在该实体,如果不存在,则报错
if (teacherRepository.findOne(id) == null) {
throw new EntityNotFoundException("传入的ID值:" + id.toString() + "有误。未找到对应的实体");
}
// 对实体ID赋值, 并执行更新操作
teacher.setId(id);
return teacherRepository.save(teacher);
}
}