实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
注解填充字段 @TableField(fill = FieldFill.INSERT_UPDATE) 生成器策略部分也可以配置:
public enum FieldFill {
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入填充字段
*/
INSERT,
/**
* 更新填充字段
*/
UPDATE,
/**
* 插入和更新填充字段
*/
INSERT_UPDATE
}
实体对象的编写:
package com.zs.entity;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer age;
private String email;
private GenderEnum gender;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String operator;
@TableLogic
private Integer flag;
public User(Long id, String name, Integer age, String email, GenderEnum gender) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
this.gender = gender;
}
}
自定义实现类 MyMetaObjectHandler:
package com.zs.handler;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "operator", String.class, "Jetty");
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "operator", String.class, "Tom");
}
}
测试类:
@Test
public void test() {
User user = new User(13L, "Guido van Rossum", 25, "Guido van Rossum@qq.com", GenderEnum.MALE);
boolean res = userService.save(user);
System.out.println(res);
}
注意事项:
1、填充原理是直接给entity的属性设置值。
2、MetaObjectHandler提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null则不填充
3、字段必须声明TableField注解,属性fill选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
4、填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component或@Bean注入
5、update(T t,Wrapper updateWrapper)时t不能为空,否则自动填充失效