mybatisplus字段值自动填充

1.在需要自动填充的字段上添加相关注解

1.在添加时自动填充

@TableField(fill = FieldFill.INSERT)
private Date createdTime;

2.在修改时自动填充

@TableField(fill = FieldFill.UPDATE)
private Date updatedTime;

2.添加自动填充的配置类

说明:1.填充配置的字段,要和实体类中保持一致

2.代码中getUserId()方法是从Security框架中获取登录人员的id,根据自己的框架修改

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hn.renting.config.security.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 填充器
 *
 */
@Slf4j
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createdTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createdBy", String.class, getUserId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updatedTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updatedBy", String.class, getUserId());
    }

    /**
     * 获取登录用户id
     * @return
     */
    private String getUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AdminUserDetails userDetails = null;
        try {
            Object principal = authentication.getPrincipal();
            userDetails = (AdminUserDetails)principal;
            return userDetails.getUser().getId();
        }catch (Exception e){
            log.error(e.toString());
            log.error(authentication.getPrincipal().toString());
        }
        return null;
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值