如果要实现自动填充就只学要在属性上面叫上TableField注解
@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;
fill有四个值分别表示默认值,插入时候赋值,更新时候赋值,插入和更新的时候都赋值
public enum FieldFill {
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE;
private FieldFill() {
}
}
然后创造一个配置类MyMetaObjecthandler实现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());
}
@Override
public void updateFill(MetaObject metaObject) {
metaObject.setValue("updateTime" , LocalDateTime.now());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
}
那么如果在插入更新用户的id的时候获取session里的用户id呢
首先要知道
1.doFilter方法
2.updateFill方法是在同一个线程里的
所以我们可以用java提供的ThreadLocal来存放用户的id,这样就可以在updateFill方法里获取用户id了
首先创造一个BaseContext类
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();
}
}
里面创造ThreadLocal的对象
然后就可以在过滤器中获取用户的id
if (request.getSession().getAttribute("employee") != null){
Long id = (Long)request.getSession().getAttribute("employee");
//把id存到context里
BaseContext.setCurrentId(id);
filterChain.doFilter(request,response);
return;
}
然后就可以通过get方法获取用户id了
metaObject.setValue("updateUser", BaseContext.getCurrentId());