mybatisplus自动填充实现
时间: 2023-11-09 16:01:05 浏览: 82
MybatisPlus自动填充可以通过实现MetaObjectHandler接口来实现。具体步骤如下:
1. 创建一个类实现MetaObjectHandler接口,并重写其中的方法,例如:
```
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
```
2. 在实体类中使用@TableField注解标注需要自动填充的字段,例如:
```
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
// 省略getter和setter方法
}
```
3. 在MybatisPlus配置文件中配置自动填充处理器,例如:
```
@Configuration
public class MybatisPlusConfig {
@Autowired
private MyMetaObjectHandler myMetaObjectHandler;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
@Bean
public GlobalConfig globalConfig() {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setMetaObjectHandler(myMetaObjectHandler);
return globalConfig;
}
}
```
阅读全文