一、自动填充封装
1、在service-base模块中添加
创建包handler,创建自动填充类 MyMetaObjectHandler
package com.atguigu.servicebase.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
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);
}
}
2、在实体类中需要自动填充的元素上添加自动填充注解
@ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT)//自动填充的注解
private Date gmtCreate;
@ApiModelProperty(value = "更新时间", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
二、controller方法定义
1、新增
@ApiOperation(value = "新增讲师")
@PostMapping
public R save(
@ApiParam(name = "teacher", value = "讲师对象", required = true)
@RequestBody EduTeacher eduTeacher){
eduTeacherService.save(eduTeacher);
return R.ok();
}
2、根据id查询
@ApiOperation(value = "根据ID查询讲师")
@GetMapping("{id}")
public R getById(
@ApiParam(name = "id", value = "讲师ID", required = true)
@PathVariable String id){
EduTeacher eduTeacher = eduTeacherService.getById(id);
return R.ok().data("item", eduTeacher);
}
3、根据id修改
@ApiOperation(value = "根据ID修改讲师")
@PutMapping("{id}")
public R updateById(
@ApiParam(name = "id", value = "讲师ID", required = true)
@PathVariable String id,
@ApiParam(name = "teacher", value = "讲师对象", required = true)
@RequestBody EduTeacher eduTeacher){
eduTeacher.setId(id);
eduTeacherService.updateById(eduTeacher);
return R.ok();
}