公共字段的自动填充的功能
Mybatis Plus公共字段自动填充,也就是在插入或者更新的时候为指定字段赋予指定的值,使用它的好处就是可以统一对这些字段进行处理,避免了重复代码。
实现步骤
-
在实体类需要填充的属性上添加@TableFileld注解,属性标注在什么时候自动填充,
-
//这里使用了Mybatis提供的公共字段填充功能, @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;
-
创建元数据处理器配置类,并实现MetaObjectHandler接口,类上加@component注解
-
@Component @Slf4j public class MybatisObjectHandler implements MetaObjectHandler { //MetaObject元数据,代表当前操作的对象, @Override public void insertFill(MetaObject metaObject) { metaObject.setValue("createTime", LocalDateTime.now()); metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("createUser", BaseContext.getCurrentID()); metaObject.setValue("updateUser",BaseContext.getCurrentID()); } @Override public void updateFill(MetaObject metaObject) { metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser", BaseContext.getCurrentID()); } }
-
需要注意的是元数据处理器无法传入request对象,也就是无法获得前端穿过来的数据,无法根据前端输入的内容动态插入数据,
-
所以这里如果要根据前端的内容动态插入数据就需要用另一一种方式来获得前端的数据,这里使用ThreadLocal
ThreadLocal,获取当前登录用户的id
什么是ThreadLocal?
ThreadLocal并不是一个Thread,而是Thread的局部变量。当使用ThreadLocal维护变量时,ThreadLocal为每个使用该
变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
ThreadLocali为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不
能访问。
ThreadLocal常用方法:
public void set(T value)
设置当前线程的线程局部变量的值
public T get()
返回当前线程所对应的线程局部变量的值
我们可以在LoginCheckFilter的doFilter,方法中获取当前登录用户id,并调用ThreadLocal的set方法来设置当前线程的线
程局部变量的值(用户id),然后在MyMetaObjectHandler的updateFill方法中调用ThreadLocalf的get方法来获得当前
线程所对应的线程局部变量的值(用户id)。
使用注意点,
- 在前端传入请求时调用set方法,传入用户id,通过过滤器或者拦截器实现
- 元数据处理器使用时使用get方法调用用户id
- 上面的baseContext.getCurrentID就是使用了ThreadLocal来获取的用户Id
threadLocal工具类
public class BaseContext {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<Long>();
public static void setCurrentId(Long id) {
threadLocal.set(id);
}
public static Long getCurrentID() {
return threadLocal.get();
}
}
过滤器部分代码
if (request.getSession().getAttribute("employee") != null) {
log.info("用户已经登录,用户Id为{}",request.getSession().getAttribute("employee"));
Long id = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(id);
filterChain.doFilter(request, response);
log.info("请求{}已经被放行", request.getRequestURI());
return;
}