liurunyu
2024-04-15 55d5046ae0a9da1109e402d7d719f765a4bccdae
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
67
68
69
70
71
72
73
package com.dy.common.mybatis;
 
 
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.dy.common.po.BaseEntity;
import com.dy.common.util.IDLongGenerator;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
 
import java.lang.reflect.Method;
 
@Intercepts(
    {
        @Signature(
            type = Executor.class,
            method = "update",
            args = { MappedStatement.class, Object.class }
        )
    }
)
public class AutoGenerateIdInterceptor implements Interceptor {
 
    static int MAPPED_STATEMENT_INDEX = 0;
    static int PARAMETER_INDEX = 1;
    static String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME = "setId";
    static String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME2 = "setUserId";
 
    /**
     * 拦截逻辑实现
     * @param invocation 代理
     * @return Object
     * @throws Throwable 异常
     */
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX];
        SqlCommandType commandType = mappedStatement.getSqlCommandType();
        if (commandType.equals(SqlCommandType.INSERT)) {
            Object entity = invocation.getArgs()[PARAMETER_INDEX];
            if (entity instanceof BaseEntity) {
                //Class<? extends Object> entityClass = entity.getClass();
                Class<?> entityClass = entity.getClass();
                Method setMt = null ;
                try{
                    // 添加用户时userId为自动生成主键。roleId存在时是为用户绑角色
                    String jsonString = JSONObject.toJSONString(entity, JSONWriter.Feature.WriteMapNullValue);
                    JSONObject jsonObject = JSONObject.parseObject(jsonString);
                    if(jsonObject.containsKey("userId") && !jsonObject.containsKey("roleId")) {
                        setMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME2, Long.class) ;
                    }else {
                        //有一些实体没有id,例如中间表
                        setMt = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_NAME, Long.class) ;
                    }
                }catch (Exception e){
                    //当entityClass没有setId方法时,会抛出异常
                }
                if(setMt != null){
                    setMt.invoke(entity, new IDLongGenerator().generate());
                }
 
                invocation.getArgs()[PARAMETER_INDEX] = entity;
            }
        }
        return invocation.proceed();
    }
 
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
 
}