自动更新 时间,公共字段
对需要自动填充的字段加入插入@TableField(fill = FieldFill.INSERT)注解或者是更新注解@TableField(fill = FieldFill.UPDATE)
创建一个公共类,对于时间固定值可直接使用LocalDateTime.now()获取
package org.example.reggie.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;
/**
* @ClassName MyMetaObjecthandler
* @Description TODO
* @date 2024/8/17 19:15
* @Version 1.0
*/
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
/*
* 插入时候自动填充
* */
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充【insert】.....");
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("createUser", BaseContext.getCurrentId());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
log.info(metaObject.toString());
}
/*
* 更新的时候自动填充
* */
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充【update】.....");
metaObject.setValue("updateTime", LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrentId());//取出修改者id
log.info(metaObject.toString());
}
}
对于不是固定的修改者,可以使用ThreadLocal进行获取
package org.example.reggie.common;
/**
* @ClassName BaseContext
* @Description 获取线程中的id
* @date 2024/8/17 19:48
* @Version 1.0
*/
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();
}
}
先在LoginFilter判断是否登录中获取request中的id,放入baseContext中,然后再在自动填充时将BaseContext.getCurrentId()的id取出
Long empId= (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);