Mybatis-Plus:SQL注入的原理

发布于:2023-01-09 ⋅ 阅读:(727) ⋅ 点赞:(0)

本节案例承接上节案例

文章目录

1. SQL注入的原理

Mybatis-Plus在启动后会将BaseMapper中的一系列的方法注册到meppedStatements中,那么究竟是如何注入的呢?流程又是怎么样的?下面我们将一起来分析下。

Mybatis-Plus中,ISqlInjector负责SQL的注入工作,它是一个接口,AbstractSqlInjector是它的实现类,实现关系如下:
在这里插入图片描述

ISqlInjector.java

package com.baomidou.mybatisplus.core.injector;

import org.apache.ibatis.builder.MapperBuilderAssistant;

/**
 * SQL 自动注入器接口
 *
 * @author hubin
 * @since 2016-07-24
 */
public interface ISqlInjector {

    /**
     * 检查SQL是否注入(已经注入过不再注入)
     *
     * @param builderAssistant mapper 信息
     * @param mapperClass      mapper 接口的 class 对象
     */
    void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass);
}

AbstractSqlInjector中,主要是由inspectInject()方法进行注入的,如下:

在实现方法中,methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));是关键,循环遍历方法,进行注入。
在这里插入图片描述
最终调用抽象方法injectMappedStatement进行真正的注入:


    /**
     * 注入自定义 MappedStatement
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo);

查看该方法的实现:
在这里插入图片描述
以SelectById为例查看:

我们现在抽象方法的实现打上断点
在这里插入图片描述

在这里插入图片描述
TestMybatisSpring.java

import mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pojo.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestMybatisSpring {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelectById() {
        // 查询id为5的用户
        User user = this.userMapper.selectById(5L);
        System.out.println(user);
    }
}

debug形式运行
在这里插入图片描述
在这里插入图片描述



本文含有隐藏内容,请 开通VIP 后查看