mybatis-plus通用信息注入
package com.ruoyi.business.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* * mybatis拦截器
*
* @author wuhuc
* @data 2021/11/26 - 10:52
*/
@Component
public class MybatisHandler implements MetaObjectHandler {
/**
* 创建者
*/
public final static String CREATE_BY = "createBy";
/**
* 创建时间
*/
public final static String CREATE_TIME = "createTime";
/**
* 更新者
*/
public final static String UPDATE_BY = "updateBy";
/**
* 更新时间
*/
public final static String UPDATE_TIME = "updateTime";
/**
* 逻辑删除字段
*/
public final static String DELETE_STATUS = "deleteStatus";
/**
* 使用自动插入数据需要在 实体类加上 @TableField(fill = FieldFill.INSERT)注解,并区分是插入还是修改
* 注意创建者和更新者的类型为 Long 时间为 LocalDateTime
*/
@Override
public void insertFill(MetaObject metaObject) {
//有create_by的字段就添加创建者
final Long userId = SecurityUtils.getUserId();
this.fillStrategy(metaObject, MybatisHandler.CREATE_BY, userId);
this.fillStrategy(metaObject, MybatisHandler.UPDATE_BY, userId);
//有create_time的字段就添加创建时间
this.fillStrategy(metaObject, MybatisHandler.CREATE_TIME, LocalDateTime.now());
//有update_time的字段就添加创建时间(项目约定,添加的时候同时加上修改时间)
this.fillStrategy(metaObject, MybatisHandler.UPDATE_TIME, LocalDateTime.now());
this.fillStrategy(metaObject, MybatisHandler.DELETE_STATUS, Constants.STRING_ZERO);
}
@Override
public void updateFill(MetaObject metaObject) {
final Long userId = SecurityUtils.getUserId();
this.setFieldValByName(MybatisHandler.UPDATE_BY, userId, metaObject);
this.setFieldValByName(MybatisHandler.UPDATE_TIME, LocalDateTime.now(), metaObject);
}
}