在写项目的过程中有时会有很多需要重复填写信息的地方,比如填写某一个用户的id字段,用到字段填充,实现使用Mybatis Plus提供的公共字段自动填充功能
1.实现步骤
(1)在实体类的属性上加入@TableField注解,指定自动填充的策略
(2)按照框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectHandler接口
@Component @Slf4j public class MetaObjectHandler implements com.baomidou.mybatisplus.core.handlers.MetaObjectHandler { /** * 插入的时候自动填充 * * @param 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()); } /** * 更新的时候自动填充 * * @param metaObject */ @Override public void updateFill(MetaObject metaObject) { metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser", BaseContext.getCurrentId()); } }
但是在其中,获取Session中的用户id却不行,需要使用到另一个东西,TreadLocal
2.TreadLocal
(1)什么是TreadLocal?
ThreadLocal并不是一个Thread,而是Thread的局部变量。当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。
(2)实现步骤:
编写BaseContext工具类,基于ThreadLocal封装的工具类
public class BaseContext { private static ThreadLocal<Long> threadLocal = new ThreadLocal<>(); /** * 用来获取值 * * @return */ public static Long getCurrentId() { return threadLocal.get(); } /** * 用来设置值 * * @param id */ public static void setCurrentId(Long id) { threadLocal.set(id); } }
在LoginCheckFilter的doFilter方法中调用BaseContext来设置当前登录用户的id
在MyMetaObjectHandler的方法中调用BaseContext获取登录用户的id
metaObject.setValue("createUser", BaseContext.getCurrentId()); metaObject.setValue("updateUser", BaseContext.getCurrentId());