疯狂的狮子li
2021-09-23 553c29ab8a46c9a07e3657fdd36a81a6bfde1afe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.ruoyi.framework.mybatisplus;
 
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
 
import java.util.Date;
 
/**
 * MP注入处理器
 *
 * @author Lion Li
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
 
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            //根据属性名字设置要填充的值
            if (metaObject.hasGetter("createTime")) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
            if (metaObject.hasGetter("createBy")) {
                this.setFieldValByName("createBy", getLoginUsername(), metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
        updateFill(metaObject);
    }
 
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter("updateBy")) {
                this.setFieldValByName("updateBy", getLoginUsername(), metaObject);
            }
            if (metaObject.hasGetter("updateTime")) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
 
    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        SysUser loginUser;
        try {
            loginUser = SecurityUtils.getUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUserName();
    }
 
}