文章目录
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 后查看