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;
}
}