MyBatis Source Summary--mapperbuilder (2)

Source: Internet
Author: User

first of all in this statement, I was through learningLakeside Breezeon the basis of "MyBatis" to summarize the code.

"MyBatis" http://blog.csdn.net/hupanfeng/article/details/9068003

The SQL statements in the project, the first level cache, etc. will be configured in the mapper file, in the development of it is often configured, so the resolution of the mapper file to do a detailed summary.

1. The Mapperelement method in the Xmlconfigbuilder class is to parse the entry of the mapper file, check the child node type and get the child node properties before parsing, and load the configuration file to get the byte stream. The Xmlmapperbuilder object is then created, and the byte stream is passed in as a parameter.

 private void Mapperelement (xnode parent) throws Exception {if (parent! = null) {for (XNode child:parent.getCh Ildren ()) {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<?> Mapperinter            face = Resources.classforname (Mapperclass);          Configuration.addmapper (Mapperinterface); } else {throw new Builderexception ("A mapper element may be only specify a URL, resource or class, and not more t Han one. ");}}}}

1.1 When creating a Xmlmapperbuilder object with one parameter of Configuration.getsqlfragments (), returns the number of members in the configuration class

Protected final map<string, xnode> sqlfragments = new Strictmap<xnode> ("XML fragments parsed from previous Map Pers ");
Strictmap is an inner class of the configuration class used to store SQL tags under each mapper element, inheriting HashMap and writing the Put and get methods

  @SuppressWarnings ("unchecked") public    V put (String key, V value) {      if (ContainsKey (key))        throw new IllegalArgumentException (name + "already contains value for" + key);      if (Key.contains (".")) {        final String Shortkey = Getshortname (key);        if (Super.get (shortkey) = = null) {          super.put (Shortkey, value);        } else {          super.put (Shortkey, (V) New Ambiguity (Shortkey));        }      }      Return Super.put (key, value);    }
As you can see from the code, overriding the Put method is important in order to throw an exception when the key value is duplicated.

Public V get (Object key) {      v value = super.get (key);      if (value = = null) {        throw new IllegalArgumentException (name + "does not contain value for" + key);      }      if (value instanceof ambiguity) {        throw new IllegalArgumentException (((ambiguity) value). Getsubject () + "is Ambiguou s in "+ name            +" (try using the full name including the namespace, or rename one of the entries) ");      return value;    }
The Get method throws an exception when the value is not obtained.

1.2 Xmlmapper, where mapperbuilderassistant is used for caching, SQL parameters, and query-returned result set processing.

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

2. The parse method in Xmlmapper

public void Parse () {    if (!configuration.isresourceloaded (Resource)) {      ConfigurationElement (parser.evalnode ("/mapper"));      Configuration.addloadedresource (Resource);      Bindmapperfornamespace ();    }    Parsependingresultmaps ();    Parsependingchacherefs ();    Parsependingstatements ();  }
The 2.1 ConfigurationElement method parses the child nodes under the mapper tag. The first-level cache of MyBatis is turned on by default, You can verify by tracing the Parsestatementnode method of the Xmlstatementbuilder class in the Buildstatemnetfromcontext method and want to turn off the first-level cache light Configuration usecache= False is useless and must be configured with Flushcache=true. Other methods interested friends can do their own research, here do not do a detailed introduction.

  private void ConfigurationElement (XNode context) {    try {      String namespace = Context.getstringattribute (" Namespace ");      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 RuntimeException ("Error parsing Mapper XML. Cause: "+ E, E);    }  }
2.2 Configuration.addloadedresource (Resource) added to a hashset indicates that the rescue file for this mapper has been parsed.

2.3 bindmapperfornamespace method, The agent factory object used to obtain the mapper, to determine whether Knowmappers has its agent factory object, knowmappers is described in the previous section. If it does not exist, create its proxy engineering object and save it in

  private void Bindmapperfornamespace () {    String namespace = Builderassistant.getcurrentnamespace ();    if (Namespace! = null) {      class<?> boundtype = null;      try {        Boundtype = Resources.classforname (namespace),      } catch (ClassNotFoundException e) {        //ignore, bound Type is not required      }      if (boundtype! = null) {        if (!configuration.hasmapper (Boundtype)) {          Configuration.addloadedresource ("namespace:" + namespace);          Configuration.addmapper (Boundtype);}}}  
Summary: (1) through the previous section and this section of the summary, you can find MyBatis parsing XML routines. First get the root node of the configuration file, the class name that resolves its child nodes is (root node name +mapperbulider) so the program that writes is very hierarchical.

(2) Inner class and rewrite HashMap get, put method, for inner class learning http://blog.csdn.net/ilibaba/article/details/3866537.

(3) To learn more about parsing the mapper file, learn the ConfigurationElement method in the Xmlmapperbuilder class.




MyBatis Source Summary--mapperbuilder (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.