public enum FieldFill {
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入填充字段
*/
INSERT,
/**
* 更新填充字段
*/
UPDATE,
/**
* 插入和更新填充字段
*/
INSERT_UPDATE
}
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("book")
public class Book implements Serializable {
private static final long serialVersionUID = 1l;
@TableId(value = "id", type = IdType.ASSIGN_UUID) // 自动生成不含中划线的 UUID 作为主键
private String id;
@TableField(value = "created", fill = FieldFill.INSERT) // MyBatis-Plus设置自动填充时间
private Date created;
@TableField(value = "updated", fill = FieldFill.INSERT_UPDATE) // 自动更新时间
private Date updated;
@TableField(value="bookname", fill = FieldFill.INSERT_UPDATE)
private String bookname;
}
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 执行插入操作时,如果时间字段为null,则自动填充
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "bookname", String.class, "红楼梦");
this.setFieldValByName("created",new Date(),metaObject);
this.setFieldValByName("updated",new Date(),metaObject);
}
/**
* 执行修改操作时,如果时间字段为null,则自动填充
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updated",new Date(),metaObject);
}
}
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private UserMapper userMapper;
@Autowired
private BookMapper bookMapper;
/**
* 向book表插入数据
* INSERT INTO book ( id, created, updated, bookname ) VALUES ( ?, ?, ?, ? )
* a8b00085b1277972a690465f3dc35067(String), 2022-07-21 11:38:40.231(Timestamp), 2022-07-21 11:38:40.231(Timestamp), 红楼梦(String)
*/
@RequestMapping("/test1")
@ResponseBody
public String test1(){
bookMapper.insert(new Book());
return "success";
}
/**
* 修改1条数据
* UPDATE book SET updated=?, bookname=? WHERE id=?
* 2022-07-21 11:38:44.632(Timestamp), 西游记(String), 1(String)
*/
@RequestMapping("/test2")
@ResponseBody
public String test2(){
Book book = new Book();
book.setId("1");
book.setBookname("西游记");
bookMapper.updateById(book);
return "success";
}
}