MyBatis-Plus自动填充
数据库持久层配置类DataBaseConfiguration.java:
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 数据库持久层配置类
*/
@Configuration(value = "dataBaseConfigurationByAdmin")
public class DataBaseConfiguration {
/**
* 分页插件
*/
@Bean
@ConditionalOnMissingBean
public MybatisPlusInterceptor mybatisPlusInterceptorByAdmin() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
填充规则MyMetaObjectHandler.java:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.util.Date;
@Primary
@Component(value = "myMetaObjectHandlerByAdmin")
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("开始插入填充...");
this.strictInsertFill(metaObject, "createTime", Date::new,Date.class);
this.strictInsertFill(metaObject, "updateTime", Date::new,Date.class);
this.strictInsertFill(metaObject, "delFlag", ()->0, Integer.class);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("开始更新填充...");
this.strictUpdateFill(metaObject, "updateTime", Date::new,Date.class);
}
}
使用:
使用注解指定实体类中的某个字段在插入数据时需要进行自动填充。
@Data
public class BaseDO {
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 修改时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* 删除标识 0:未删除 1:已删除
*/
@TableField(fill = FieldFill.INSERT)
private Integer delFlag;
}