MyBatis啟動:MapperStatement建立

來源:互聯網
上載者:User

標籤:list   hat   代碼   決定   ndt   method   命名空間   路徑   ted   

參考:http://blog.csdn.net/ashan_li/article/details/50351080

MappedStatement說明

一個MappedStatement對象對應Mapper設定檔中的一個select/update/insert/delete節點,主要描述的是一條SQL語句。其屬性有

//節點中的id屬性加要命名空間  private String id;  //直接從節點屬性中取  private Integer fetchSize;  //直接從節點屬性中取  private Integer timeout;  private StatementType statementType;  private ResultSetType resultSetType;  //對應一條SQL語句  private SqlSource sqlSource;    //每條語句都對就一個緩衝,如果有的話。  private Cache cache;  //這個已經過時了  private ParameterMap parameterMap;  private List<ResultMap> resultMaps;  private boolean flushCacheRequired;  private boolean useCache;  private boolean resultOrdered;  //SQL的類型,select/update/insert/detete  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; 

  

Mapper是介面,用來聲明持久層的方法,而Mapper配置對應的XML,決定了方法的執行的內容,決定持久層方法的行為。在MyBatis啟 動時,會解析這些包含SQL的XML檔案,並將其封裝成為MapperStatement對象,並將MapperStatement註冊到全域的 configuration對象上,接下來就深入的瞭解代碼的實現。

 

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);              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);              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 {              throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");            }          }        }      }    }  

  

從 源碼中就可以看出,配置Mapper時,可以配置package熟悉,註冊包下所有的介面。還可以從資源中比如硬碟上,網路中,去載入XML檔案。註冊過 程是通過註冊器MapperRegistry來完成的。註冊的容器是一個map,Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();。

 

key是mapper的介面完整類名,value是mapper的代理工廠。註冊完成後,還要做解析XML檔案操作。

 

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);        parser.parse();        loadCompleted = true;      } finally {        if (!loadCompleted) {          knownMappers.remove(type);        }      }    }  }

  

 

  

下面 是解析的代碼

 

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 {            parseStatement(method);          } catch (IncompleteElementException e) {            configuration.addIncompleteMethod(new MethodResolver(this, method));          }        }      }      parsePendingMethods();    }  

  

 
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();      }    }  }  

  

 

 

MyBatis通過替換mapper完整類名中的“.”,替換成為“/”,然後加上尾碼“.xml”,拼成XML資源路徑,然後判斷是否已載入過XML,沒有的話載入XML檔案,然後使用xmlMapperBuilder建造者解析XML中的元素。


 
public void parse() {    if (!configuration.isResourceLoaded(resource)) {      configurationElement(parser.evalNode("/mapper"));      configuration.addLoadedResource(resource);      bindMapperForNamespace();    }      parsePendingResultMaps();    parsePendingChacheRefs();    parsePendingStatements();  }  

  

resource是建立建造者的構造參數,type.getClass(),就是mapper的類型。判斷然後還沒有載入mapper,就開始解析XML檔案中的mapper節點。

 

private void configurationElement(XNode context) {      try {        String namespace = context.getStringAttribute("namespace");        if (namespace.equals("")) {            throw new BuilderException("Mapper‘s namespace cannot be empty");        }        builderAssistant.setCurrentNamespace(namespace);        cacheRefElement(context.evalNode("cache-ref"));        cacheElement(context.evalNode("cache"));        parameterMapElement(context.evalNodes("/mapper/parameterMap"));        resultMapElements(context.evalNodes("/mapper/resultMap"));        sqlElement(context.evalNodes("/mapper/sql"));        buildStatementFromContext(context.evalNodes("select|insert|update|delete"));      } catch (Exception e) {        throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);      }    }  

  

 

 

解 析時,先設定命名空間。然後解析cache-ref元素,可以使用其他命名空間的的緩衝。在configuration對象上有一個 cacheRefMap用來維護引用緩衝的關係。並且引用其他命名空間的引用指向助手類的currCache屬性上。如果被指向的命名空間還未載入,則拋 出異常,並且往configuration對象上添加未處理的緩衝引用chcheRef。

private void cacheRefElement(XNode context) {    if (context != null) {      configuration.addCacheRef(builderAssistant.getCurrentNamespace(), context.getStringAttribute("namespace"));      CacheRefResolver cacheRefResolver = new CacheRefResolver(builderAssistant, context.getStringAttribute("namespace"));      try {        cacheRefResolver.resolveCacheRef();      } catch (IncompleteElementException e) {        configuration.addIncompleteCacheRef(cacheRefResolver);      }    }  }  

  

 

解析緩衝元素,可以使用type屬性配置自訂的緩衝,否則使用預設 的PERPETUAL。然後用別名註冊器註冊緩衝類。接下來註冊緩衝的回收演算法,緩衝大小,到期時間,是否唯讀等屬性。然後由助手類通過反射建立一個具體 的Cache對象。然後註冊到configuration全域對象上。

private void cacheElement(XNode context) throws Exception {    if (context != null) {      String type = context.getStringAttribute("type", "PERPETUAL");      Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);      String eviction = context.getStringAttribute("eviction", "LRU");      Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);      Long flushInterval = context.getLongAttribute("flushInterval");      Integer size = context.getIntAttribute("size");      boolean readWrite = !context.getBooleanAttribute("readOnly", false);      Properties props = context.getChildrenAsProperties();      builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, props);    }  }  

  

 

 

下一步是解析parameterMap,新版中已經不推薦配置這個屬性了,屬於老方法。

參數Map映射已經被淘汰,但是結果集映射還很有用。接下來就是解析 resultMap。解析resultMap的元素比較多,解析完成後,還會根據解析到的映射關聯建立一個結果處理器對象 resultMapResolver,後面對資料庫操作時,用來處理列和屬性的類型轉換。

private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());    String id = resultMapNode.getStringAttribute("id",        resultMapNode.getValueBasedIdentifier());    String type = resultMapNode.getStringAttribute("type",        resultMapNode.getStringAttribute("ofType",            resultMapNode.getStringAttribute("resultType",                resultMapNode.getStringAttribute("javaType"))));    String extend = resultMapNode.getStringAttribute("extends");    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");    Class<?> typeClass = resolveClass(type);    Discriminator discriminator = null;    List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();    resultMappings.addAll(additionalResultMappings);    List<XNode> resultChildren = resultMapNode.getChildren();    for (XNode resultChild : resultChildren) {      if ("constructor".equals(resultChild.getName())) {        processConstructorElement(resultChild, typeClass, resultMappings);      } else if ("discriminator".equals(resultChild.getName())) {        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);      } else {        ArrayList<ResultFlag> flags = new ArrayList<ResultFlag>();        if ("id".equals(resultChild.getName())) {          flags.add(ResultFlag.ID);        }        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));      }    }    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);    try {      return resultMapResolver.resolve();    } catch (IncompleteElementException  e) {      configuration.addIncompleteResultMap(resultMapResolver);      throw e;    }  }  

  

 

 

解析來繼續解析SQL片段,用來複用的SQL。助手類會將SQL片段的ID前面加上當前命名空間和一個點,用來和其他命名空間區別開。然後將SQL片段載入到configuration全域對象的sqlFragments對象上儲存。

 

 

private void sqlElement(List<XNode> list, String requiredDatabaseId) throws Exception {    for (XNode context : list) {      String databaseId = context.getStringAttribute("databaseId");      String id = context.getStringAttribute("id");      id = builderAssistant.applyCurrentNamespace(id, false);      if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) sqlFragments.put(id, context);    }  }  

  

 

 

最後是重頭戲,解析增刪改查節點,建立Statement對象。同樣是通過建造者模式來建立語句對象,建造者的構造參數包括全域配置資訊,當前命名空間助手,XML配置資訊和資料庫ID。

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);      }    }  }  

  

 

首先還是解析XML檔案的各個屬性,然後處理<include>和<selectKey>片段。根據include標籤中的refid到全域配置中取對應的SQL片段。根據selectKey的配置資訊,建立一個MapperStatement,並且添加到全域配置中,然後移除selectKey節點。

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");    String lang = context.getStringAttribute("lang");    LanguageDriver langDriver = getLanguageDriver(lang);      Class<?> resultTypeClass = resolveClass(resultType);    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));    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 = 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))          ? 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);  }  

  

 

 

接下來的操作,也是根據配置的屬性,然後通過建造者建立mappedStatement對象。並添加到configuration全域對象上。

MyBatis啟動:MapperStatement建立

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.