- 環境
- SpringBoot 2.2.6.RELEASE
- Mybatis-Plus 3.3.1.tmp
- JDK 1.8
1.添加自動填充的配置
public class MybatisPlusObjectHandler implements MetaObjectHandler{
@Override
public void insertFill(MetaObject metaObject) {
System.out.println("***************************");
System.out.println("insert fill");
System.out.println("***************************");
Object gmtCreate = getFieldValByName("gmtCreate", metaObject);
//判斷表中有沒有字段,有的話執行,沒有就不做資源的無謂開銷
boolean gmtCreate1 = metaObject.hasSetter("gmtCreate");//判斷表中有沒有字段,有的話執行,沒有就不做資源的無謂開銷
if(gmtCreate1){
System.out.println("gmtCreate="+gmtCreate);
if(gmtCreate==null){
//LocalDateTime當前時間
// LocalDateTime now = LocalDateTime.now();
setFieldValByName("gmtCreate",getDateTimeOfTimestamp(System.currentTimeMillis()),metaObject);
}
}
}
@Override
public void updateFill(MetaObject metaObject) {
System.out.println("************************");
System.out.println("update fill");
System.out.println("************************");
setFieldValByName("gmtModified",getDateTimeOfTimestamp(System.currentTimeMillis()),metaObject);
}
}
並配置到springbean里面
2.實體類添加注解
只要這三步即可,
注意: MybatisPlusObjectHandler 類上不必加@Component標簽,不然報錯!