一、用途
MetaObjectHandler是MyBatis-Plus提供的一个接口,用于自动填充实体对象中的公共字段(例如创建时间、修改时间、逻辑删除标志等)
二、使用步骤
2.1 引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${version}</version>
</dependency>
2.2 @TableField
public class User {
@TableId
private Long id;
private String username;
@TableField(fill = FieldFill.INSERT)
private String createUserId;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateUserId;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
// 其他字段和方法...
}
在实体类中添加 @TableField注解:
- FieldFill.INSERT:表示只是插入时生效;
- FieldFill.INSERT_UPDATE: 表示插入和更新时生效;
2.3 创建配置类实现MetaObjectHandler接口
自定义元对象处理器类,实现metaObjecthandler接口,重写insertFill、updateFill方法;
@Slf4j
@Component
public class MyMetaObjecthandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充【insert】");
log.info(metaObject.toString());
metaObject.setValue("createTime", new Date());
metaObject.setValue("updateTime", new Date());
metaObject.setValue("createUserId", UserContext.getUserId());
metaObject.setValue("updateUserId", UserContext.getUserId());
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充【update】");
log.info(metaObject.toString());
metaObject.setValue("updateTime", new Date());
metaObject.setValue("updateUserId", UserContext.getUserId());
}
}
这是MetaObjectHandler的基本用法示例。通过使用MetaObjectHandler,你可以方便地实现实体对象的公共字段自动填充功能。请注意,具体的字段名称和逻辑根据你的实际业务需求进行调整。