有很多表的設計裡面,有一些欄位都是相同的,類似
createTime,updateTime等等,這些欄位如果每次在插入或更新時都操作一次很煩鎖,
mybatis提供了機制可以很方便的自動填充這些欄位
具體做法
1.在欄位上新增註解
//插入時填充
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//更新時填充
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
2.新建 MetaObjectHandler實現類
public class MyBatisMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject,"createTime", Date.class,new Date());
this.strictInsertFill(metaObject,"createUserId",String.class,"111");
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
this.setFieldValByName("updateUserId","222",metaObject);
//使用下面的方法有問題,只會在欄位為null的時候才會填充,有值的時候不會更新了
//this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
//this.strictUpdateFill(metaObject,"updateUserId",String.class,"111");
}
}
3.配置 MetaObjectHandler
//自動填充配置
@Bean
public MetaObjectHandler myMetaObjectHandler() {
return new MyBatisMetaObjectHandler();
}
//分頁配置
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
這樣在插入和更新的時候,這些欄位會自動被填充