一、自动填充封装

1、在实体类添加自动填充注解

  1. ![图片.png](https://cdn.nlark.com/yuque/0/2021/png/22523384/1635951447291-3eb40ddb-4d75-49a0-8c28-f4f644b79dbc.png#clientId=u7a7f61d7-31ea-4&from=paste&height=203&id=u41c59a85&margin=%5Bobject%20Object%5D&name=%E5%9B%BE%E7%89%87.png&originHeight=203&originWidth=430&originalType=binary&ratio=1&size=10568&status=done&style=none&taskId=ue648cf19-8605-4b06-bbd2-f417565234c&width=430)

2、在service-base模块中添加

  1. **创建包handler,创建自动填充类 MyMetaObjectHandler**
  1. package com.atguigu.servicebase.handler;
  2. @Component //交给spring管理,需要在启动类上添加@ComponentScan(basePackages = {"com.atguigu"})才能扫描到非启动类项目下的包
  3. public class MyMetaObjectHandler implements MetaObjectHandler {
  4. @Override
  5. public void insertFill(MetaObject metaObject) {
  6. //类中属性名称,不是数据库字段名称
  7. this.setFieldValByName("gmtCreate", new Date(), metaObject);
  8. this.setFieldValByName("gmtModified", new Date(), metaObject);
  9. }
  10. @Override
  11. public void updateFill(MetaObject metaObject) {
  12. this.setFieldValByName("gmtModified", new Date(), metaObject);
  13. }
  14. }

二、controller方法定义


1、新增

  1. package com.atguigu.eduservice.controller;
  2. @Api(description="讲师管理")
  3. @RestController
  4. @RequestMapping("/eduservice/teacher")
  5. public class EduTeacherController {
  6. //把service注入
  7. @Autowired
  8. private EduTeacherService teacherService;
  9. //添加讲师接口的方法
  10. @ApiOperation(value = "新增讲师")
  11. @PostMapping("addTeacher")
  12. public R addTeacher(@ApiParam(name = "teacher", value = "讲师对象", required = true)
  13. @RequestBody EduTeacher eduTeacher) {
  14. boolean save = teacherService.save(eduTeacher);
  15. if(save) {
  16. return R.ok();
  17. } else {
  18. return R.error();
  19. }
  20. }
  21. }

2、根据id查询

  1. //根据讲师id进行查询
  2. @ApiOperation(value = "根据ID查询讲师")
  3. @GetMapping("getTeacher/{id}")
  4. public R getTeacher(@ApiParam(name = "id", value = "讲师ID", required = true)
  5. @PathVariable String id){
  6. EduTeacher eduTeacher = teacherService.getById(id);
  7. return R.ok().data("teacher",eduTeacher);
  8. }

3、根据id修改

  1. @PutMapping("{id}")
  2. public R updateById(
  3. @ApiParam(name = "id", value = "讲师ID", required = true)
  4. @PathVariable String id,
  5. @ApiParam(name = "teacher", value = "讲师对象", required = true)
  6. @RequestBody Teacher teacher){
  7. teacher.setId(id);
  8. teacherService.updateById(teacher);
  9. return R.ok();
  10. }
  11. //讲师修改功能
  12. @ApiOperation(value = "根据ID修改讲师")
  13. @PostMapping("updateTeacher")
  14. public R updateTeacher(@RequestBody EduTeacher eduTeacher) {
  15. boolean flag = teacherService.updateById(eduTeacher);
  16. if(flag) {
  17. return R.ok();
  18. } else {
  19. return R.error();
  20. }
  21. }