官方文档:MyBatis-Plus
常用插件
1.公共字段填充
对于每个实体类共有的属性字段,例如创建时间、修改时间、创建人、修改人,我们可以使用公共字段填充,来统一填充这些字段,这样我们在创建这些实体类的对象的时候就不需要set这些属性,实现丝滑开发
1 2 3 4
| @TableField(fill = FieldFill.INSERT) private String gmtCreate; @TableField(fill = FieldFill.INSERT_UPDATE) private String gmtModified;
|
第一种配置的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.itheima.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component public class MyMetaObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { metaObject.setValue("gmtCreate", LocalDateTime.now()); metaObject.setValue("gmtModified", LocalDateTime.now()); }
@Override public void updateFill(MetaObject metaObject) { metaObject.setValue("gmtModified", LocalDateTime.now()); } }
|
第二种配置的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Component public class MyMetaObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); }
@Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); } }
|
2.逻辑删除
1.配置全局的配置文件(可以省略)
1 2 3 4 5
| mybatis-plus: global-config: db-config: logic-delete-value: 1 logic-not-delete-value: 0
|
2.配置逻辑删除的组件(3.1.1版本之后不需要这一步,可以省略)
1 2 3 4 5 6 7 8 9 10 11 12 13
| import com.baomidou.mybatisplus.core.injector.ISqlInjector; import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class MyBatisPlusConfiguration {
@Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); } }
|
3.在实体类上逻辑删除的字段上加上逻辑删除的注解
1 2 3 4
|
@TableLogic(value = "1",delval = "0")
|