Mybatis3源碼分析(三):解析mapper的xml設定檔

來源:互聯網
上載者:User

標籤:java   mybaits   framework   web   xpath   

    這一章我們來看看mybatis是怎麼讀取mapper的xml設定檔並解析其中的sql語句。

    我們還記得是這樣配置sqlSessionFactory的:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource" />     <property name="configLocation" value="classpath:configuration.xml"></property>      <property name="mapperLocations" value="classpath:com/xxx/mybatis/mapper/*.xml"/>       <property name="typeAliasesPackage" value="com.tiantian.mybatis.model" />    </bean>  

    這裡配置了一個mapperLocations屬性,它是一個運算式,sqlSessionFactory會根據這個運算式讀取包com.xxx.mybaits.mapper下面的所有xml格式檔案,那麼具體是怎麼根據這個屬性來讀取設定檔的呢?

    答案就在SqlSessionFactoryBean類中的buildSqlSessionFactory方法中:

if (!isEmpty(this.mapperLocations)) {      for (Resource mapperLocation : this.mapperLocations) {        if (mapperLocation == null) {          continue;        }        try {          XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),              configuration, mapperLocation.toString(), configuration.getSqlFragments());          xmlMapperBuilder.parse();        } catch (Exception e) {          throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);        } finally {          ErrorContext.instance().reset();        }        if (logger.isDebugEnabled()) {          logger.debug("Parsed mapper file: '" + mapperLocation + "'");        }      }    }

    mybatis使用XMLMapperBuilder類的執行個體來解析mapper設定檔。

public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {    this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()),        configuration, resource, sqlFragments);  }

  

private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {    super(configuration);    this.builderAssistant = new MapperBuilderAssistant(configuration, resource);    this.parser = parser;    this.sqlFragments = sqlFragments;    this.resource = resource;  }

    接著系統調用xmlMapperBuilder的parse方法解析mapper。

public void parse() {    //如果configuration對象還沒載入xml設定檔(避免重複載入,實際上是確認是否解析了mapper節點的屬性及內容,    //為解析它的子節點如cache、sql、select、resultMap、parameterMap等做準備),    //則從輸入資料流中解析mapper節點,然後再將resource的狀態置為已載入    if (!configuration.isResourceLoaded(resource)) {      configurationElement(parser.evalNode("/mapper"));      configuration.addLoadedResource(resource);      bindMapperForNamespace();    }    //解析在configurationElement函數中處理resultMap時其extends屬性指向的父物件還沒被處理的<resultMap>節點    parsePendingResultMaps();    //解析在configurationElement函數中處理cache-ref時其指向的對象不存在的<cache>節點(如果cache-ref先於其指向的cache節點載入就會出現這種情況)    parsePendingChacheRefs();    //同上,如果cache沒載入的話處理statement時也會拋出異常    parsePendingStatements();  }

     mybatis解析mapper的xml檔案的過程已經很明顯了,接下來我們看看它是怎麼解析mapper的:

private void configurationElement(XNode context) {    try {      //擷取mapper節點的namespace屬性      String namespace = context.getStringAttribute("namespace");      if (namespace.equals("")) {        throw new BuilderException("Mapper's namespace cannot be empty");      }      //設定當前namespace      builderAssistant.setCurrentNamespace(namespace);      //解析mapper的<cache-ref>節點      cacheRefElement(context.evalNode("cache-ref"));      //解析mapper的<cache>節點      cacheElement(context.evalNode("cache"));      //解析mapper的<parameterMap>節點      parameterMapElement(context.evalNodes("/mapper/parameterMap"));      //解析mapper的<resultMap>節點      resultMapElements(context.evalNodes("/mapper/resultMap"));      //解析mapper的<sql>節點      sqlElement(context.evalNodes("/mapper/sql"));      //使用XMLStatementBuilder的對象解析mapper的<select>、<insert>、<update>、<delete>節點,      //mybaits會使用MappedStatement.Builder類build一個MappedStatement對象,      //所以mybaits中一個sql對應一個MappedStatement      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));    } catch (Exception e) {      throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);    }  }

    configurationElement函數幾乎解析了mapper節點下所有子節點,至此mybaits解析了mapper中的所有節點,並將其加入到了Configuration對象中提供給sqlSessionFactory對象隨時使用。這裡我們需要補充講一下mybaits是怎麼使用XMLStatementBuilder類的對象的parseStatementNode函數借用MapperBuilderAssistant類對象builderAssistant的addMappedStatement解析MappedStatement並將其關聯到Configuration類對象的:

public void parseStatementNode() {//ID屬性    String id = context.getStringAttribute("id");    //databaseId屬性    String databaseId = context.getStringAttribute("databaseId");    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {      return;    }    //fetchSize屬性    Integer fetchSize = context.getIntAttribute("fetchSize");    //timeout屬性    Integer timeout = context.getIntAttribute("timeout");    //parameterMap屬性    String parameterMap = context.getStringAttribute("parameterMap");    //parameterType屬性    String parameterType = context.getStringAttribute("parameterType");    Class<?> parameterTypeClass = resolveClass(parameterType);    //resultMap屬性    String resultMap = context.getStringAttribute("resultMap");    //resultType屬性    String resultType = context.getStringAttribute("resultType");    //lang屬性    String lang = context.getStringAttribute("lang");    LanguageDriver langDriver = getLanguageDriver(lang);    Class<?> resultTypeClass = resolveClass(resultType);    //resultSetType屬性    String resultSetType = context.getStringAttribute("resultSetType");    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);    String nodeName = context.getNode().getNodeName();    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));    //是否是<select>節點    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;    //flushCache屬性    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);    //useCache屬性    boolean useCache = context.getBooleanAttribute("useCache", isSelect);    //resultOrdered屬性    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 = langDriver.createSqlSource(configuration, context, parameterTypeClass);    //resultSets屬性    String resultSets = context.getStringAttribute("resultSets");    //keyProperty屬性    String keyProperty = context.getStringAttribute("keyProperty");    //keyColumn屬性    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 {      //useGeneratedKeys屬性      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))          ? new Jdbc3KeyGenerator() : new NoKeyGenerator();    }    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,        resultSetTypeEnum, flushCache, useCache, resultOrdered,         keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);  }
     由以上代碼可以看出mybaits使用XPath解析mapper的設定檔後將其中的resultMap、parameterMap、cache、statement等節點使用關聯的builder建立並將得到的對象關聯到configuration對象中,而這個configuration對象可以從sqlSession中擷取的,這就解釋了我們在使用sqlSession對資料庫進行操作時mybaits怎麼擷取到mapper並執行其中的sql語句的問題。









Mybatis3源碼分析(三):解析mapper的xml設定檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.