美文网首页
使用springboot aop 修改数据表名、增加参数

使用springboot aop 修改数据表名、增加参数

作者: thinking2019 | 来源:发表于2020-12-31 19:11 被阅读0次

一定是环绕通知

    @Resource(name = "sqlSessionFactory")
    private SqlSessionFactory sqlSessionFactory;

    @Pointcut("execution(* com.mapper..*.*(..))")
    public void switchStockDataSource() {
    }

    @Around("switchOrderDataSource()")
    public Object switchOrderDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        // 参数值
        Object[] args = joinPoint.getArgs();
        updateTableName(joinPoint, sqlSessionFactory);

        return joinPoint.proceed();
    }

修改数据库表名

public void updateTableName(ProceedingJoinPoint joinPoint, SqlSessionFactory sessionFactory) throws NoSuchFieldException, IllegalAccessException {
        //1.获取namespace+methdoName
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String namespace = method.getDeclaringClass().getName();
        String methodName = method.getName();
        //2.根据namespace+methdoName获取相对应的MappedStatement
        Configuration configuration = sessionFactory.getConfiguration();
        MappedStatement mappedStatement = configuration.getMappedStatement(namespace+"."+methodName);

        // 获得 private final SqlSource sqlSource; 对象
        Field sqlSource = FieldUtils.getField(mappedStatement.getClass(), "sqlSource", true);
        sqlSource.setAccessible(true);
        // 动态数据源
        DynamicSqlSource staticSqlSource = (DynamicSqlSource) sqlSource.get(mappedStatement);
        // 包含sql
        BoundSql boundSql = staticSqlSource.getBoundSql(null);
        // 修改sql
        Field sqlSourceField = mappedStatement.getClass().getDeclaredField("sqlSource");//反射
        sqlSourceField.setAccessible(true);
        // boundSql.getSql() 获取执行的sql
        sqlSourceField.set(mappedStatement, new StaticSqlSource(mappedStatement.getConfiguration(),
        // 修改sql中的表名
                updateTableName(boundSql.getSql(), "新表名"),
                boundSql.getParameterMappings()));
    }

增加参数

 Object[] args = joinPoint.getArgs();
 FieldUtils.writeDeclaredField(args[0], "sub_num", "增加值", true);

相关文章

网友评论

      本文标题:使用springboot aop 修改数据表名、增加参数

      本文链接:https://www.haomeiwen.com/subject/aqyroktx.html