MyBatis Architecture design and source Code Analysis Series (i): MyBatis architecture

Source: Internet
Author: User

If you are not familiar with MyBatis, please refer to the MyBatis official documentation, which is of great benefit to understanding its architectural design and source code analysis.

I. Overview

MyBatis is not a complete ORM framework, its official homepage is so introduced to its own

Data Mapper Framework Object using Simplicity  is Object relational mapping tools.

And in its official documentation, "What's Mybaits" says

 is class  for MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results.  for
ORM is a mapping between object and relation, including both Object->relation and Relation->object. Hibernate is a complete ORM framework, and MyBatis completes the Relation->object, which is what it says about the data mapper framework. Some of the design ideas and details of ORM can be found in the ORM section of the Martin Flow "Enterprise Application Architecture Model", which MyBatis does not deliberately complete the full concept of ORM (object mapping), but rather is designed to make database operations easier and easier, and to reduce the workload of developers , I think this is also the most practical application system, I believe that with hibernate have suffered its pain, and used mybatis will feel it is simple and easy. second, the overall structure

The following is an overall architecture diagram describing mybatis from the functional process hierarchy

And the following is the MyBatis source package corresponding to the architecture diagram

The following is a brief analysis of the architecture of the underlying layers in the "architecture diagram of the functional process perspective", which will be featured in a later series of articles to delve into the mybatis important functional points.

1. Interface Layerwe know that the code to perform database operations with MyBatis, regardless of the integration with spring, is as follows
"Org/mybatis/example/mybatis-config.xml";
InputStream InputStream = resources.getresourceasstream (Resource);
New Sqlsessionfactorybuilder (). Build (InputStream);
sqlsession session = Sqlsessionfactory.opensession ();
Try {
  Blog blog = session.selectone ("Org.mybatis.example.BlogMapper.selectBlog", 101);
finally {
  Session.close ();
}

Sqlsessionfactory, sqlsession This is the core class of the MyBatis interface layer, especially sqlsession, is the API to implement all database operations, These classes are under the Org.apache.ibatis.session package, the main class structure of the package is as follows

Configuration is a fairly important class in mybatis, so to speak, if you understand the meaning of all of these parameters, you not only clearly know all the configuration items provided by MyBatis, but also understand the internal core operating principle of mybatis, Of course, to really understand the meaning and implementation of these parameters, you need to read the complete MyBatis framework before you can do it.

As can be seen, the configuration object and Defaultsqlsessionfactory is a 1:1 association, which means that in a defaultsqlsessionfactory derived from all the sqlsession scope , the configuration object is globally unique. At the same time Sqlsessionfactory provides the getconfiguration () interface to expose the configuration object, so the developer, in addition to the config file, It is also possible to dynamically change the properties of a configuration in a program for dynamic adjustment purposes, but not only when the reset is completed, but also in the process of modification that may affect the execution of other sqlsession.

2. Core Layer2.1 Configuration Resolution

When the app starts, MyBatis parses both profiles

    • Sqlmapconfig.xml
    • Sqlmap.xml

Sqlmapconfig.xml is parsed in the Xmlconfigbuilder class, and its class diagram relationships are as follows

We know that XML has two ways of parsing: One is DOM, the other is Sax,mybatis uses the Document Object Model (DOM) interface provided by ORG.WRC.DOM--JDK ( Sqlmapconfig.xml is not very big, so DOM is not inefficient, the JDK also provides the SAX model interface Org.xml.sax, both of which are JAXP component APIs), And the javax.xml.xpath.XPath provided by the JDK to look for components as XML paths.

Sqlmap.xml is resolved in the Xmlmapperbuilder, wherein the analysis of the statement (that is, Sqlmap.xml select| Insert| update| Delete definition section) is delegated to Xmlstatementbuilder to complete. Sqlmap.xml's analysis is complex, involving preparedmapping, resultmapping, Languagedriver, discriminator, caching, automatic mapping, and so on a series of object construction, here temporarily skipped, later thematic analysis.

2.2 SQL Execution

The core of executor in MyBatis is the complete process of database operation around it. Here's the class diagram for executor.

In the I listed the parameters of the method in executor, but not explicitly written in their subclasses. As you can see, executor mainly provides

    • query| Update (INSERT and delete are also using update), as you can see from the method definition, it requires mappedstatement, parameter, Resulthandler, which are the main parts of SQL execution, Detailed implementation is described in the following topics.
    • Transaction commit/Rollback, which is delegated to the transaction object to complete.
    • Cache, Createcachekey ()/iscached ().
    • Lazy loading, deferload ().
    • Close, close (), mostly transaction rollback/shutdown.

The properties of the Baseexecutor show that it internally maintains the LocalCache to Localoutputparametercache to handle the cache, and what this cache holds, this later topic. and thread-Safe deferred load list deferredloads, transaction object transaction.

The properties of Batchexecutor have shown that it internally maintains statementlist batch commits and saves execution results through batchresultlist.

The properties and methods of resueexecutor indicate that it maintains the Java.sql.Statement object cache internally to reuse statement objects (for databases that support precompilation, When you create PreparedStatement, you need to send the database request precompilation, and the reuse of the statement object mainly reduces the network overhead of this precompilation.

Below take sqlsession.selectlist as an example, draw a sequence diagram of SQL execution (click on the image below to see a larger image, some branches are simplified)

3. Basic Layer 3.1, logging:

MyBatis uses a set of logging interfaces of its own definition, according to the log framework commonly used by developers--log4j, LOG4J2, Apache Commons log, java.util.logging, SLF4J, stdout (console)-- Adapters are provided separately. Because of the different log-level classifications for each logging framework (for example, Java.util.logging.Level provides all, FINEST, Finer, FINE, CONFIG, INFO, WARNING, SEVERE, off nine levels, Unlike the usual logging framework taxonomy, MyBatis provides the trace, debug, Warn, and error four levels, which are basically consistent with the mainstream framework taxonomy (in contrast to the lack of info, perhaps MyBatis think that their logs are either debug-required, Or at least warn, without the need for info).

There's a special packet in org.apache.ibatis.logging. JDBC, which is not a literal understanding of logging through JDBC to the database, but the JDBC operation in the developer configuration of the log framework to print out, which is our common in the development phase of the tracking SQL statement , passing in parameters, affecting the number of rows of these important debugging information.

3.2. IO

The IO in MyBatis consists of two main functions: the API to read the resource file, the ClassLoader required to encapsulate the mybatis itself, and the order of loading.

3.3, Reflection

In mybatis such as parameter processing, the result mapping is heavily used for reflection, it is necessary to read the class metadata frequently, the reflection calls the Get/set, So MyBatis provides the org.apache.ibatis.reflection to further encapsulate common reflection operations to provide a more concise and convenient API. For example, we always deal with exceptions when we reflect (Illegalaccessexception, nosuchmethodexception), MyBatis Unified processing as custom runtimeexception, reducing the amount of code.

3.4, Exceptions

In the open source framework, which is represented in spring, most exceptions that cannot be handled further in the application are converted to RuntimeException to facilitate the caller's operation, as is the case with frequently encountered SQLEXCEPTION,JDK conventions, which are exception. From the JDK's point of view, forcing developers to capture SqlException in order to be able to shut down the database connection in catch/finally, and the framework of spring such as the resources of the developers to manage things, naturally do not need developers to bother SqlException, So the encapsulation is converted into runtimeexception. MyBatis anomaly system is not complex, org.apache.ibatis.exceptions under a few classes, mainly used is persistenceexception.

3.5. Cache

Caching is an important part of MyBatis, and there are two kinds of caches:

    • Session or statement scope-level cache, by default, CacheKey is constructed in session,baseexecutor based on Mappedstatement ID, SQL, parameter values, and Rowbound (boundary). and use the LocalCache in Baseexccutor to maintain this cache.
    • A global level two cache, implemented through Cacheexecutor, with its delegate transactionalcachemanager to save/Get the cache, the global level two cache is complex, and later requires a thematic analysis, as well as the efficiency of its cache and the application scenarios to be analyzed at that time.
3.6. Data source/Connection pool

MyBatis itself provides a simple data source/connection pool, under Org.apache.ibatis.datasource, followed by a thematic analysis. The main implementation class is Pooleddatasource, which contains the maximum number of active connections, the maximum number of idle connections, the longest time to take out (to avoid a thread over-occupied), the connection is not enough when the waiting time, although simple, but also reflects the general principle of the connection pool. Ali has a "druid" project, according to them said than Proxool, c3p0 efficiency is also higher, you can learn a bit.

3.7 Business

MyBatis is relatively simple to handle transactions, Transactionisolationlevel defines several isolation levels, does not support more complex scenarios such as inline transactions, and because it is a persistent layer, So it is true that in application development the spring is entrusted to handle transaction implementations that are truly isolated from the developer. The implementation of the analytic transaction is an entry point to understand what does not sweep the JDBC specification.

Subsequent to the mybatis of the various parts of the detailed design and source code analysis, due to read and parse the logic of Sqlmapconfig.xml and Sqlmap.xml is strong correlation with each module, so this part of the content and in each module together analysis.

MyBatis Architecture design and source Code Analysis Series (i): MyBatis architecture

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.