第六篇:Configuration之mappers

这是Configuration里面最后一部分数据的解析,也是最复杂的一部分,所以这里使用了一篇来专门说这个,希望可以尽量说的清除点,首先要先看几个比较重要的概念

mapper

这个就是一个个的文件,大概格式如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zxc.study.test.mapper.UserMapper">
    <select id="selectUser" resultType="com.zxc.study.test.bean.User" flushCache="true">
    select * from user where id = #{param1}
  </select>

    <select id="test" resultType="com.zxc.study.test.bean.User">
    select * from user where id in
    <foreach collection="objectList" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
    </select>

</mapper>

BoundSql

绑定sql的对象,里面包含了具体的sql执行语句,比如

select * from user where id = ? and name = ?

与对应填充占位符对象ParameterMapping,里面包含了类型等

SqlSource

sql生成来源接口,用来获取BoundSql的源接口,主要有几个实现

DynamicSqlSource:动态sql数据源,也是最核心的一种了

StaticSqlSource:静态sql数据源,直接拿到就行了

RawSqlSource:介于两者之间的

LanguageDriver

语言驱动器,用来获取SqlSource的接口,主要有以下的实现

XMLLanguageDriver:也就是从xml文件解析,就想上面的例子一样

RawLanguageDriver:从接口上的注解进行解析的,比如

 @Select("select * from user where id = #{id}")
 User a(@Param("id") Integer id);

会从接口上解析select里面的语句出来,不过这种尽量少用比较好

以上是一些比较核心的接口和对应的一些基本类,接下来再去看源码解析是怎么走的

源码解析

解析入口为
org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement


  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      //循环处理
      for (XNode child : parent.getChildren()) {
        //包格式的处理,等同于接口类型的处理
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //xml文件格式处理
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            //xml文件格式处理
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {
            //接口处理
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            //xml和接口必须要有一个,否则抛异常
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }



可以看到实际上有两种解析方法,一种是通过xml,一种是通过接口,不过两种最终都会保存一份到另外一个位置去,比如xml解析完会根据namespace把接口也注册进行,接口注册完也会生成一份xml的进行保存,目的就是为了两者可以相互使用,这是基本的解析入口


XML方式

org.apache.ibatis.builder.xml.XMLMapperBuilder#parse

  public void parse() {
    //如果没解析过才会进行解析,其实就是用set来进行判断
    if (!configuration.isResourceLoaded(resource)) {
      //解析mapper标记,这也是最核心的一个位置
      configurationElement(parser.evalNode("/mapper"));
      //放到mapper里面去
      configuration.addLoadedResource(resource);
      //绑定到接口上,如果namespace配置的是接口的话,这也是一个规范
      bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
  }



  private void configurationElement(XNode context) {
    try {
      String namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.equals("")) {
        throw new BuilderException("Mapper's namespace cannot be empty");
      }
      builderAssistant.setCurrentNamespace(namespace);
      //解析缓存相关的
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      //解析parameterMap,现在已经基本不用了
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      //解析resultMap
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      //解析sql片段,应该是要放到某个map中,其他地方引用的时候再从map拿出来
      sqlElement(context.evalNodes("/mapper/sql"));
      //核心的sql语句解析逻辑,增删改查
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
    }
  }



其中的就不说了,最重要的其实就是解析那4个标签,也就是crud


  private void buildStatementFromContext(List<XNode> list) {
    if (configuration.getDatabaseId() != null) {
      buildStatementFromContext(list, configuration.getDatabaseId());
    }
    buildStatementFromContext(list, null);
  }

  private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }



真正的解析入口在:org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode


public void parseStatementNode() {
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
      return;
    }

    //就是获取一些属性
    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    String parameterType = context.getStringAttribute("parameterType");
    Class<?> parameterTypeClass = resolveClass(parameterType);
    String resultMap = context.getStringAttribute("resultMap");
    //解析返回值
    String resultType = context.getStringAttribute("resultType");

    //语言驱动器,默认就是从xml里面解析的,一般也不会改
    //主要是用来创建SqlSource的,也就是最核心的sql语句方面的内容
    String lang = context.getStringAttribute("lang");
    LanguageDriver langDriver = getLanguageDriver(lang);


    Class<?> resultTypeClass = resolveClass(resultType);
    String resultSetType = context.getStringAttribute("resultSetType");
    //statement类型,默认PREPARED
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

    //解析标记是属于crud哪个命令
    String nodeName = context.getNode().getNodeName();
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));

    //是否为查询以及缓存相关的一些配置
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    // Include Fragments before parsing
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    // Parse selectKey after includes and remove them.
    processSelectKeyNodes(id, parameterTypeClass, langDriver);
    
    // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
    //通过语言驱动器获取SqlSource,核心的一个处理位置
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");

    //主键生成获取处理逻辑
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    if (configuration.hasKeyGenerator(keyStatementId)) {
      keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
          ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
    }

    //构建助手添加mappedStatement到配置中
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
        resultSetTypeEnum, flushCache, useCache, resultOrdered, 
        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
  }


最后会生成一个MappedStatement放到配置对象中存起来




里面最核心的代码主要有以下几个地方,最拿出来稍微看下



1. LanguageDriver 


//获取语言驱动器,默认是XMLLanguageDriver进行解析的,如果是注解使用的是
//RawLanguageDriver,默认值是在配置类初始化的时候进行设置的

LanguageDriver langDriver = getLanguageDriver(lang);



2. SqlSource 创建


SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);

这是解析sql语句最核心的一个位置了

使用的是这个组件进行解析的
org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode


  public SqlSource parseScriptNode() {
    //解析再外层的
    MixedSqlNode rootSqlNode = parseDynamicTags(context);
    SqlSource sqlSource = null;
    if (isDynamic) {
      //如果是动态数据源
      sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
    } else {
      //如果不是
      sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
    }
    return sqlSource;
  }



再看看这个方法    parseDynamicTags



  protected MixedSqlNode parseDynamicTags(XNode node) {
    //收集所有的sqlNode
    List<SqlNode> contents = new ArrayList<SqlNode>();
    NodeList children = node.getNode().getChildNodes();
    //获取子节点进行处理
    for (int i = 0; i < children.getLength(); i++) {
      XNode child = node.newXNode(children.item(i));
      //如果是文本类型的,也就是不包含子标签,像 <if> <foreach>之类的
      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
        String data = child.getStringBody("");
        //拿取里面的内容判断是不是有${}的
        TextSqlNode textSqlNode = new TextSqlNode(data);
        //如果有就走这个
        if (textSqlNode.isDynamic()) {
          contents.add(textSqlNode);
          isDynamic = true;
        } else {
          //如果没有走这个
          contents.add(new StaticTextSqlNode(data));
        }
      } else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
        //这些是包裹了标签的,使用的是NodeHandler进行处理
        String nodeName = child.getNode().getNodeName();
        NodeHandler handler = nodeHandlerMap.get(nodeName);
        if (handler == null) {
          throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
        }
        //调用处理方式,并设置为动态节点返回
        handler.handleNode(child, contents);
        isDynamic = true;
      }
    }
    //最后使用组合设计模式把收集到的sqlNode组合返回
    return new MixedSqlNode(contents);
  }




也还是比较清晰的,里面出现了个新的概念NodeHandler,这个是用来解析每个子标签用的,比如<if>

可以随便找个看看 IfHandler



  private class IfHandler implements NodeHandler {
    public IfHandler() {
      // Prevent Synthetic Access
    }

    @Override
    public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
      //这个位置说明是可以嵌套标签的,也就是说<if></if> 可以再包裹其他的数据,不过本来就该如此
      MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle);
      //获取属性
      String test = nodeToHandle.getStringAttribute("test");
      //生成节点
      IfSqlNode ifSqlNode = new IfSqlNode(mixedSqlNode, test);
      // 并把节点放到列表中
      targetContents.add(ifSqlNode);
    }
  }



这些handler是在一开始就创建的,可以在当前类就可以看到这个方法


  private void initNodeHandlerMap() {
    nodeHandlerMap.put("trim", new TrimHandler());
    nodeHandlerMap.put("where", new WhereHandler());
    nodeHandlerMap.put("set", new SetHandler());
    nodeHandlerMap.put("foreach", new ForEachHandler());
    nodeHandlerMap.put("if", new IfHandler());
    nodeHandlerMap.put("choose", new ChooseHandler());
    nodeHandlerMap.put("when", new IfHandler());
    nodeHandlerMap.put("otherwise", new OtherwiseHandler());
    nodeHandlerMap.put("bind", new BindHandler());
  }



3. MappedStatement

这个也是比较核心的对象,包含了以下内容


  //加载资源
  private String resource;
  private Configuration configuration;
  //唯一id
  private String id;
  private Integer fetchSize;
  //超时时间
  private Integer timeout;
  //StatementType类型,默认是PREPARED
  private StatementType statementType;
  private ResultSetType resultSetType;
  //SqlSource对象
  private SqlSource sqlSource;
  //缓存对象
  private Cache cache;
  private ParameterMap parameterMap;
  private List<ResultMap> resultMaps;
  private boolean flushCacheRequired;
  private boolean useCache;
  private boolean resultOrdered;
  //标签内容   insert update delete select 
  private SqlCommandType sqlCommandType;
  private KeyGenerator keyGenerator;
  private String[] keyProperties;
  private String[] keyColumns;
  private boolean hasNestedResultMaps;
  private String databaseId;
  private Log statementLog;
  private LanguageDriver lang;
  private String[] resultSets;


主要核心的其实就是在解析sqlnode,至于怎么组装sql语句与参数设置是在调用过程中的,这个就后面再讲了

接口方式

添加入口为

org.apache.ibatis.binding.MapperRegistry#addMapper


  public <T> void addMapper(Class<T> type) {
    //只有接口才会进来,因为要生成代理对象
    if (type.isInterface()) {
      //已经有了就直接抛异常
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
        //生成代理对象
        knownMappers.put(type, new MapperProxyFactory<T>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        //解析,这里面又会把接口相关的再解析一遍,根据接口全类名去找关联的xml文件,
        //格式为 String xmlResource = type.getName().replace('.', '/') + ".xml";
        //所以要遵循它的规定
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }



这里面主要做了两件事,生成代理对象和通过接口名字又找到了xml文件进行解析xml的解析流程,都稍微看下


1. 生成代理对象


public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}



2, 解析xml


  public void parse() {
    String resource = type.toString();
    if (!configuration.isResourceLoaded(resource)) {
      //加载资源进行解析
      loadXmlResource();
      configuration.addLoadedResource(resource);
      assistant.setCurrentNamespace(type.getName());
      parseCache();
      parseCacheRef();
      Method[] methods = type.getMethods();
      for (Method method : methods) {
        try {
          // issue #237
          if (!method.isBridge()) {
            //解析接口方法看上面是不是标记了注解之类的
            parseStatement(method);
          }
        } catch (IncompleteElementException e) {
          configuration.addIncompleteMethod(new MethodResolver(this, method));
        }
      }
    }
    parsePendingMethods();
  }




loadXmlResource会根据规则解析xml文件


  private void loadXmlResource() {
    // Spring may not know the real resource name so we check a flag
    // to prevent loading again a resource twice
    // this flag is set at XMLMapperBuilder#bindMapperForNamespace
    //判断是不是加载过了就不重复加载
    if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
      //拼接路径获取资源文件
      String xmlResource = type.getName().replace('.', '/') + ".xml";
      InputStream inputStream = null;
      try {
        inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
      } catch (IOException e) {
        // ignore, resource is not required
      }
      if (inputStream != null) {
        //不为空时又调用原来的解析
        XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
        xmlParser.parse();
      }
    }
  }





parseStatement会对方法进行解析注解已经处理sqlSource等


org.apache.ibatis.builder.annotation.MapperAnnotationBuilder#parseStatement

这个就不细说了,也是大概的解析过程....

这是Mybatis里面解析xml里面最复杂的一个东西了,如果这个搞懂了,对Mybatis的理解也就差不多了,这里面涉及了很多的核心概念,大家可能要反复看才能理解这个东西

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值