直接上代码
获取用户的方式根据项目情况修改
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MetaHandler implements MetaObjectHandler {
/**
* 新增数据执行
*/
@Override
public void insertFill(MetaObject metaObject) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String username = sysUser.getUsername();
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("createBy", username, metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
this.setFieldValByName("updateBy", username, metaObject);
this.setFieldValByName("deleted", 0, metaObject);
}
/**
* 更新数据执行
*/
@Override
public void updateFill(MetaObject metaObject) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// 有可能是mq执行的更新操作
if (ObjectUtil.isEmpty(sysUser)) {
return;
}
String username = sysUser.getUsername();
this.setFieldValByName("updateTime", new Date(), metaObject);
this.setFieldValByName("updateBy", username, metaObject);
}
}