项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。
我们可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作:
1、实体上添加以下注解 (同个字段上只能使用一个注解):
- @TableField(fill = FieldFill.UPDATE):只能‘修改’时的自动填充。
 - @TableField(fill = FieldFill.INSERT):只能‘插入’时的自动填充。
 - @TableField(fill = FieldFill.INSERT_UPDATE):‘修改’、‘插入’时都能自动填充字段。 | package com.wzy.bootmtp.pojo;
 
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
@Data//生产get、set、toString等方法的注解
public class User {
    private Integer id;
    private String name;
    private String age;
    @TableField(fill = FieldFill.INSERT)
    private String email;
}
| | —- |
2、写法一:创建 MyMetaObjectHandler 类 实现,元对象处理 MetaObjectHandler 接口,并实现接口里的 insertFill()、updateFill()。
package com.wzy.bootmtp.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import org.springframework.stereotype.Component;@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {/** @Description: 插入的自动填充* @Author: WangZiYao* @Date: 2021/9/8 23:54*/@Overridepublic void insertFill(MetaObject metaObject) {//获取要被填充的字段的值Object value = getFieldValByName("email", metaObject);//当字段为空时if (value == null) {setFieldValByName("email","wwww@qq.com",metaObject);}}/** @Description: 修改的自动填充* @Author: WangZiYao* @Date: 2021/9/8 23:54*/@Overridepublic void updateFill(MetaObject metaObject) {//获取要被填充的字段的值Object value = getFieldValByName("email", metaObject);//当字段为空时if (value == null) {setFieldValByName("email","wwww@qq.com",metaObject);}}}
写法二:
@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);@Overridepublic void insertFill(MetaObject metaObject) {LOGGER.info("start insert fill ....");this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {LOGGER.info("start update fill ....");this.setFieldValByName("updateTime", new Date(), metaObject);}}
测试:
package com.wzy.bootmtp.test;import com.wzy.bootmtp.mapper.UserMapper;import com.wzy.bootmtp.pojo.User;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)@SpringBootTestpublic class TestSpringBoot {@Autowiredprivate UserMapper userMapper;@Testpublic void test1(){userMapper.insert(new User(null,"张三",25,null));}}

