如何把自动填充和在自动填充的时候获取用户id

如果要实现自动填充就只学要在属性上面叫上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());

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值