一、自动填充封装
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模块中添加
**创建包handler,创建自动填充类 MyMetaObjectHandler**
package com.atguigu.servicebase.handler;
@Component //交给spring管理,需要在启动类上添加@ComponentScan(basePackages = {"com.atguigu"})才能扫描到非启动类项目下的包
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
//类中属性名称,不是数据库字段名称
this.setFieldValByName("gmtCreate", new Date(), metaObject);
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
}
二、controller方法定义
1、新增
package com.atguigu.eduservice.controller;
@Api(description="讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
//把service注入
@Autowired
private EduTeacherService teacherService;
//添加讲师接口的方法
@ApiOperation(value = "新增讲师")
@PostMapping("addTeacher")
public R addTeacher(@ApiParam(name = "teacher", value = "讲师对象", required = true)
@RequestBody EduTeacher eduTeacher) {
boolean save = teacherService.save(eduTeacher);
if(save) {
return R.ok();
} else {
return R.error();
}
}
}
2、根据id查询
//根据讲师id进行查询
@ApiOperation(value = "根据ID查询讲师")
@GetMapping("getTeacher/{id}")
public R getTeacher(@ApiParam(name = "id", value = "讲师ID", required = true)
@PathVariable String id){
EduTeacher eduTeacher = teacherService.getById(id);
return R.ok().data("teacher",eduTeacher);
}
3、根据id修改
@PutMapping("{id}")
public R updateById(
@ApiParam(name = "id", value = "讲师ID", required = true)
@PathVariable String id,
@ApiParam(name = "teacher", value = "讲师对象", required = true)
@RequestBody Teacher teacher){
teacher.setId(id);
teacherService.updateById(teacher);
return R.ok();
}
//讲师修改功能
@ApiOperation(value = "根据ID修改讲师")
@PostMapping("updateTeacher")
public R updateTeacher(@RequestBody EduTeacher eduTeacher) {
boolean flag = teacherService.updateById(eduTeacher);
if(flag) {
return R.ok();
} else {
return R.error();
}
}