问题
我们进行添加、修改等操作时经常需要设置创建时间、创建人、修改时间、修改人等字段,在编辑时需要设置修改时间、修改人等字段,会造成大量代码的冗余;因此我们可以使用Mybatis Plus提供的公共字段自动填充功能
我们需要明白客户端发送的每次http请求,对应的在服务端都会分配一个新的线程来处理,在处理过程中涉及到下面类中的方法都属于相同的一个线程;我们可以在上述类的方法中加入如下代码(获取当前线程ID,并输出):
long id = Thread.currentThread().getId();
log.info("线程id为:{}",id);
我们首先需要建立一个由MybatisPlus提供的MetaObjectHandler 类,可以放置在公共模块common中
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 自定义元数据对象处理器
*/
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充[insert]...");
log.info(metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("createUser",new Long(1));
metaObject.setValue("updateUser",new Long(1));
}
/**
* 更新操作,自动填充
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充[update]...");
log.info(metaObject.toString());
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("updateUser",new Long(1));
}
}
然后同样在common公共模块中创建
package com.example.reggie_take_out.common;
/**
* 基于ThreadLocal封装工具类,用户保存和获取当前登录用户id
*/
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();
}
}
其次在登录成功的方法中,使用session存储用户id的位置使用setCurrentId进行存储用户id
//在同一线程里边使用ThreadLocal方法存入用户id
Long employee = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(employee);
最后别忘了在咱们的实体类中加入相应的注解
//创建时间
@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;