1、引入依赖
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
2、编写entity
@Data
@AllArgsConstructor
@TableName("user")
@NoArgsConstructor
public class User {
/**
* 创建人名称
*/
@TableField(fill = FieldFill.INSERT)
private String createUserName;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 修改人名称
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateUserName;
/**
* 修改时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
3、编写处理器
@Component
@Slf4j
public class AutoInsertMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
//setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("createUserName","测试1",metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
this.setFieldValByName("updateUserName","测试1",metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start insert update ....");
this.setFieldValByName("updateTime",new Date(),metaObject);
this.setFieldValByName("updateUserName", "测试2",metaObject);
}
}
4、测试