不知道从哪个版本开始,mybatis出了一种可以直接在Mapper方法上面打上@Select之类的注解,里面填个和xml配置一样的sql语句,就可以进行SQL语句的执行。
使用实例:
public interface UserMapper {
@Select("SELECT id FROM user WHERE id = #{id}")
List<User> findUserBySelectAnnotation(@Param("id") int id);
}
之前我理解的都是mybatis在启动的时候去解析xml文件中的操作节点,现在这种方式是如何解析的呢,和xml的又有何不同呢,我们来看看源码。
先看mybatis 与springboot集成的自动装配的类
@Bean创建SqlSessionFactory
创建了一个SqlSeesionFactoryBean,看这名字应该是集成了Spring的FactoryBean接口,在最后直接手动调了实现自该接口的
getObject() 方法
如果sqlSeesionFactory没有,就调用实现自spring的InitializingBean接口的afterPropertiesSet()方法
最后创建了一个SqlSessionFactory
buildSqlSessionFactory()
1.创建xmlConfigBuilder对象,可能是个空,如果自己有配mybatis.mapper-locations属性的话
2.中间对Configuration对象设置了一堆属性,可以看出,这些和传统的mybatis-config.xml中配置的那些是一样的,只不过springboot可以放在properties文件中配置
3.如果有配置mybatis.mapper-locations,并从中获取到xml资源文件的话,就遍历资源文件,挨个创建XMLMapperBuilder对象,调用parse方法进行解析
XMLMapperBuilder.parse()
XMLMapperBuilder.bindMapperForNamespace()
加的过程中,会创建MapperAnnotationBuilder对Mapper接口的方法进行解析,这里就是支持以上注解的最关键源码所在
MapperAnnotationBuilder.parse()
public void parse() {
String resource = type.toString();
//如果未加载过该Mapper接口
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
//循环该接口的所有方法
for (Method method : type.getMethods()) {
if (!canHaveStatement(method)) {
continue;
}
//如果是@Select或者@SelectProvider注解修饰的方法(其他类型的不需要ResultMap),
//查看是否有@ResultMap注解,如果没有,就根据方法的返回值,生成ResultMap对象
if (getAnnotationWrapper(method, false, Select.class, SelectProvider.class).isPresent()
&& method.getAnnotation(ResultMap.class) == null) {
parseResultMap(method);
}
try {
//开始解析@Select @Insert @Update @Delete 之类的注解,这个方法很长,下面详细讲
parseStatement(method);
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}
MapperAnnotationBuilder.parseStatement()
执行原理:解析xml中的select|update|delete|update节点时,会将信息封装成MapperStatement对象,那么作为xml配置sql的另一种方式,其实要做的也是这个工作,只不过信息是从注解里面获取而已
- 创建SqlSource信息
我们这里的实例代码是@Select
将@Select注解中的Sql封装到RawSqlSourced对象中(如果是动态SQL的话会new 出DynamicSqlSource),RawSqlSourced的构造函数会李创建SqlSource,里面会把#{id} 换成?,得到一个可执行的sql存在其中,SqlSource还持有参数列表
- 获取SqlCommandType
- 获取一些其他信息,跟解析xml創建MapperStatement对象所需的属性是一样的
- 创建MappedStatement,并加到configuration中的mappedStatements集合中
好了,注解的扫描过程已经完毕,无非就是解析注解,创建MapperStatement,ResultMap,并添加到Configuration的容器中。最后调用被注解修饰的方法的时候,会根据接口名称+方法名称 从容器中获取到这个MapperStatement,并根据里面的SqlSource取出sql,设置参数,执行。