mybatisplus欄位值自動填充

csdn淡水發表於2020-12-18

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;

/**
 * 填充器
 *
 * @author nieqiurong 2018-08-10 22:59:23.
 */
@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;
    }
}

 

相關文章