MyBatis Plus 的自动填充功能

一. 背景

我们的实体类中经常会用到创建时间 (createTime),修改时间 (updateTime) 之类的常用字段,如果每次插入和更新都去手动生成并填充,会产生很多重复的代码,MyBatis Plus其实已经为我们提供了自动填充功能,只要我们进行简单的配置,即可实现代码的简化。

代码采用 SpringBoot 进行开发。

二.实现步骤

整体实现思路:

通过抽取公用字段封装到 BaseEntity 类中,再将使用到此公共字段的类继承基类,最后由 MyBatis Plus 帮我们实现自动填充。

1.在基类 BaseEntity 代码中添加注解,用于标识需要填充的字段:

/**
 * @description 实体基类.
 */

@Data
@ApiModel(value = "BaseEntity", description = "实体基类")
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = 7229711996915758071L;

    /**
     * 主键
     */
    @Id
    @TableId(type = IdType.AUTO)
    @ApiModelProperty(value = "主键自增列")
    protected Long id;

    /**
     * 创建时间(新增时自动填充创建时间)
     */
    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    protected Date createTime;

    /**
     * 更新时间(更新时自动填充更新时间)
     */
    @ApiModelProperty(value = "更新时间")
    @TableField(fill = FieldFill.UPDATE)
    protected Date updateTime;

    /**
     * 是否已删除 0:未删除 1:已删除
     */
    @ApiModelProperty(value = "是否已删除 0:未删除 1:已删除")
    private Integer isDelete = 0;
}

在创建时间 createTime 上添加 @TableField(fill = FieldFill.INSERT) 注解;

在更新时间 updateTime 上添加 @TableField(fill = FieldFill.UPDATE) 注解;

其中的FieldFill有以下几种取值:

public enum FieldFill {
    /**
     * 默认不处理
     */
    DEFAULT,
    /**
     * 插入填充字段
     */
    INSERT,
    /**
     * 更新填充字段
     */
    UPDATE,
    /**
     * 插入和更新填充字段
     */
    INSERT_UPDATE
}

2.实现用户实体类 User,继承 BaseEntity


/**
 * @description 用户
 */
@Data
@ApiModel(value = "User", description = "用户表")
@TableName("user")
public class User extends BaseEntity {

    /**
     * 用户名
     */
    @Length(min = 4, max = 30, message = "用户名长度为4-30个字符")
    @ApiModelProperty(value = "用户名")
    private String userName;

    /**
     * 密码(加密后)
     */
    @ApiModelProperty(value = "密码")
    private String password;

    /**
     * 用户姓名
     */
    @ApiModelProperty(value = "用户姓名")
    private String realName;

    @Override
    public String toString() {
        return "User[" +
                "id=" + id +
                ",userName='" + userName +
                ",realName='" + realName +
                ",createTime=" + createTime +
                ",updateTime=" + updateTime +
                ']';
    }

}

3.自定义实现类 MyMetaObjectHandler

/**
 * @description: 实现元对象处理器接口,用于实现时间的自动填充
 * @date: 2020/9/7 16:44
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 这里的 createTime 填写需要生成的字段名称
        setFieldValByName("createTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 这里的 updateTime 填写需要生成的字段名称
        setFieldValByName("updateTime", metaObject);
    }
}

一定要加上 @Component 进行注入,否则会导致配置不生效;

4.插入数据测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
  @Autowired
  private UserMapper userMapper;
 
  @Test
  public void testInsert(){
    User user = new User();
    user.setUserName("testInsert");
    user.setRealName("测试插入");
    int result = userMapper.insert(user);
    System.out.println(user);
  } 
}

5.修改数据测试

@Test
public void testUpdate(){
  User user = new User();
  user.setId(2L);
  user.setUserName("testUpdate");
  int result = userMapper.updateById(user);
  System.out.println(user);
}

相关文章

1.pom.xml引入依赖 <dependency> <gro...
<?xml version="1.0" encoding=&a...
准备工作 ① 创建数据库&数据表 ## 创建数据库 CREA...
MyBatis逆向工程是指根据数据库表结构自动生成对应的实体类、...
MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串...
resultMap作用是处理数据表中字段与java实体类中属性的映射关...