在使用MybatisPlus时,多张表涉及到了相同的字段,例如createTime,updateTime,createUser,updateUser等,如果每次都手动添加这些字段的值,则显得麻烦,所以MybatisPlus提供了公共字段填充的功能
1.开启自动填充
1.1.在公共字段对应的属性上添加注解
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
@FieldFill 字段填充策略,其有以下的值:
1.2.扩展元对象处理器
/**
* 元数据对象处理器
*/
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充Insert");
log.info("metaObject:{}",metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser", 1L);
metaObject.setValue("updateUser", 1L);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充Update");
log.info("metaObject:{}",metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser", 1L);
metaObject.setValue("updateUser", 1L);
}
}
- 该类需要实现MetaObjectHandler接口
- 添加@Component注解,将其交给Spring托管
但是现在遇到一个问题,createUser和updateUser的值我们是写死的,为了避免硬编码,我们应该动态的获取值
1.3.ThreadLocal
为了获取用户的id,我们可以从session中获取,但是这个类中不允许添加HttpServletReq-uest对象,因此,这里引入了ThreadLocal
- ThreadLocal并不是一个Thread,而是其的一个局部变量,当使用ThreadLocal维护变量时,它会为每个使用该变量的线程提供独立的变量副本,所以每个线程都可以独立的改变自己的副本,而不会影响其它线程对应的副本
- 我们这里将要采取的方法是:由于
LoginCheckFilter中的doFilter方法EmployeeController中的update方法MyMetaObjecthandler中的updateFill方法- 这三个方法是属于同一个线程的,所以我们可以从doFilter方法中获取到session并将其存放在ThreadLocal中,然后在updateFill方法中,将其取出
1.4.创建一个工具类
public class BaseContext {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id){
threadLocal.set(id);
}
public static Long getCurrentId(){
return threadLocal.get();
}
}
1.5.在dofilter方法中获取session
//获取用户id,并存在ThreadLocal中,为了MyMetaObjectHandler中使用
Long empId = (Long) request.getSession().getAttribute("selectEmployee");
BaseContext.setCurrentId(empId);
1.6.在元对象处理器中处理id
Long currentId = BaseContext.getCurrentId();