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
74
75
package com.dy.pipIrrGlobal.config;
 
import com.dy.pipIrrGlobal.pojoSe.SeVirtualCard;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
 
import java.lang.reflect.Method;
 
/**
 * @Author: liurunyu
 * @Date: 2025/5/15 11:10
 * @Description
 */
/**
 * 拦截虚拟卡表的更新操作,使:
 *   字段in_use意为占用状态,当为true时统一设置值为0
 *   字段money意为剩余金额,当为true时统一设置值为10000
 */
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {
                        MappedStatement.class,
                        Object.class
                }
        )
})
@Slf4j
public class VirtualCardSetDefaultInterceptor  implements Interceptor {
 
    static int MAPPED_STATEMENT_INDEX = 0;
    static int PARAMETER_INDEX = 1;
    static String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_SETINUSE = "setInUse";
    static String BASE_FIELD_SET_PRIMARY_KEY_FUNTION_SETMONEY = "setMoney";
 
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object entity = invocation.getArgs()[PARAMETER_INDEX];
        if (entity instanceof SeVirtualCard) {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX];
            SqlCommandType commandType = mappedStatement.getSqlCommandType();
            if (commandType.equals(SqlCommandType.UPDATE)) {
                Class<?> entityClass = entity.getClass();
                Method setInUse = null;
                try {
                    setInUse = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_SETINUSE, Byte.class);
                } catch (Exception e) {
                    //当entityClass没有setInUse方法时,会抛出异常
                }
                if (setInUse != null) {
                    setInUse.invoke(entity, (byte)0);
                }
 
                Method setMoney = null;
                try {
                    setMoney = entityClass.getMethod(BASE_FIELD_SET_PRIMARY_KEY_FUNTION_SETMONEY, Double.class);
                } catch (Exception e) {
                    //当entityClass没有setMoney方法时,会抛出异常
                }
                if (setMoney != null) {
                    setMoney.invoke(entity, 10000.00D);
                }
                invocation.getArgs()[PARAMETER_INDEX] = entity;
            }
        }
        return invocation.proceed();
    }
}