Many people do not know how to look at the source code, today to teach you how to look at the source code.
The premise is that we need to have an overall direct understanding of the principle, workflow and module of the whole Mybatis, and also have experience in using it.
I suggest reading these two articles first:
Main contents of this paper:
Download the source code
How to download the source code?
Enter the website
Mybatis.org/mybatis-3/z…
Methods a
Jump to Github, we can github source code up and down
Github.com/mybatis/myb…
Download the source code
Method 2
Also through
Github.com/mybatis/myb…
Download the corresponding version jar and source code:
After downloading it locally, unzip it to your local directory and import it using Eclipse or IDEA.
It is found that there are as many as 20 packages in Mybatis directory. Here we will talk about the relationship and corresponding functions of these packages.
Packages fall into three categories
Basic Feature Pack
These packages are used to provide peripheral basic functions for other packages, such as file reading, reflection operations, and so on. These packages are characterized by relatively independent functionality with little coupling to business logic.
Here is the package directory for basic functionality:
Configure resolution packages
These packages are used for configuration parsing, storage, and so on. The methods in these packages run mainly during system initialization.
Here is the package directory for configuration:
Core operation package
These packages are used to complete database operations. As they work, these packages may rely on the base functionality provided by the base functionality pack and the configuration information provided by the configuration resolution pack. The methods in these packages run primarily during the database operation phase.
The core processing layer does four things:
- Parses and maps the parameters passed in the interface to JDBC types;
- Parsing SQL statements in XML files, including inserting parameters and generating dynamic SQL;
- Execute SQL statement;
- Process the result set and map it to Java objects.
Note: The plug-in also belongs to the core layer, depending on how it works and what objects it intercepts.
Here is the package directory for the core layer:
Specific package Introduction
The reflection package
Reflection in Java is powerful, but writing quality reflection code is a challenge for most developers.
MyBatis specifically provides reflection module, which has a good encapsulation of Java native reflection, provides a more concise and easy-to-use API, convenient for the upper layer to call, and carries out a series of optimization of reflection operation, such as caching class metadata, improve the performance of reflection operation.
The Java reflection mechanism provides the following functions. · Determine the class of any object at run time; · Construct an object of any class at run time; · Modify the member variables of any object at run time; · Call a method of any object at run time.
Recommend a reflection article:
Type package
MyBatis provides alias mechanism to simplify configuration files. This mechanism is one of the main functions of type conversion module.
(2) Another function of the type conversion module is to achieve the conversion between JDBC type and Java type, which is involved in the binding of arguments for SQL statements and mapping query result sets:
- When arguments are bound to SQL statements, data is converted from Java type to JDBC type.
- When the result set is mapped, the data is converted from the JDBC type to the Java type.
logging
包
Whether in a development test environment or in an online production environment, logging is very important in the overall system. Good logging helps developers and testers quickly locate Bug code, and o&M engineers quickly locate performance bottlenecks. There are many excellent logging frameworks in the Java world today, such as Log4j, Log4j2, Slf4j, and so on.
As a well-designed framework, MyBatis can not only provide detailed log output information, but also integrate various log frameworks. One of the main functions of its log module is to integrate third-party log frameworks.
io
包
The resource loading module mainly encapsulates the class loader, determines the use sequence of the class loader, and provides the function of loading class files and other resource files.
parsing
包
As the name implies, the parser module provides two main functions:
- A function, right
XPath
To encapsulate, asMyBatis
Parsed at initializationmybatis-config.xml
Configuration files and mapping profiles are supported. - Another feature is support for handling placeholders in dynamic SQL statements.
datasource
包
Data sources are one of the most common components in real development. Nowadays, open source data sources provide rich functions, such as connection pooling and connection status detection. It is very important to select data source components with excellent performance to improve the performance of ORM framework and even the whole application.
MyBatis itself provides the corresponding data source implementation, of course, MyBatis also provides the interface to integrate with the third-party data source, these functions are located in the data source module.
transaction
包
MyBatis abstracts the transaction in the database, and provides the corresponding transaction interface and simple implementation. In many scenarios, MyBatis is integrated with the Spring framework and transactions are managed by the Spring framework.
cache
包
When optimizing system performance, optimizing database performance is a very important link, and adding cache is one of the most effective means to optimize database. Using caching properly and properly can intercept a portion of database requests at the cache level.
Level 1 and level 2 caches are provided in MyBatis, and both levels of caches are implemented by caching modules in the underlying support layer. It is important to note that the two levels of cache in MyBatis run on the same JVM and share the same heap memory as MyBatis and the entire application. If the amount of data in the cache is large, other functions in the system may be affected. Therefore, if a large amount of data needs to be cached, cache products such as Redis and Memcache are preferred.
binding
包
When calling the corresponding SqlSession method to perform database operations, you need to specify the SQL node defined in the mapping file. If there is a spelling error, we can only find the corresponding exception at run time. In order to find such errors as early as possible, MyBatis associates the user-defined Mapper interface with the mapping configuration file through the Binding module. The system can complete database operations by calling the methods in the user-defined Mapper interface to execute the corresponding SQL statements, thus avoiding the above problems.
It is worth noting that developers do not need to write a custom Mapper interface implementation, MyBatis will automatically create dynamic proxy objects for it. In some scenarios, the custom Mapper interface can completely replace the mapping configuration file, but some mapping rules and SQL statement definitions are more convenient to write in the mapping configuration file, such as the definition of dynamic SQL statements.
annotations
包
With the gradual popularity of Java annotations, MyBatis provides annotation method, which makes it convenient for us to write simple database SQL operation code in Mapper interface, without having to write SQL in XML format Mapper file as before. In real life, though, people prefer to write SQL operations in response to Mapper files in XML format.
exceptions
包
The Exceptions package has three exception-related classes:
- IbatisException class (already set to deprecated),
- PersistenceException class
- TooManyResultsException class
There are many exception classes in other packages of MyBatis. All of these exception classes are subclasses of PersistenceException except the RuntimeSqlException class.
Abnormal class diagram in MyBatis:
Almost each has a custom exception corresponding to the threshold.
scripting
包
Piecing together SQL statements is a tedious and error-prone process. In order to release developers from this boring and boring work, MyBatis realizes the function of dynamic SQL statements and provides a variety of nodes corresponding to dynamic SQL statements. Examples include the < WHERE > node,
node,
node, and so on. By combining these nodes, developers can write dynamic SQL statements that meet almost any requirement.
The scripting module in MyBatis parses the dynamic SQL nodes defined in the mapping file and forms database executable SQL statements based on the arguments passed in by the user. Placeholders in the SQL statement are then processed, binding the arguments passed in by the user.
plugin
包
Although Mybatis has powerful functions, it cannot perfectly suit all application scenarios. Therefore, Mybatis provides a plug-in interface. We can expand Mybatis by adding user-defined plug-ins. User-defined plug-ins can also change the default behavior of Mybatis, for example, we can intercept SQL statements and rewrite them.
Since the user-defined plug-in will affect the core behavior of MyBatis, before using the customized plug-in, developers need to understand the internal principle of MyBatis, so as to write a safe and efficient plug-in.
The session package
The interface layer is relatively simple, and its core is SqlSession interface, which defines the API exposed to application program invocation by MyBatis, which is also the bridge of interaction between upper application and MyBatis. When the interface layer receives the call request, it calls the corresponding module of the core processing layer to complete the specific database operation.
Executor package
It is responsible for maintaining level 1 and level 2 caches and providing transaction management operations, delegating database operations to StatementHandler.
The mapping package
Mapping refers to the mapping after SQL operations are parsed
Builder package
Builder is the process of parsing configuration and annotations.
Cursor package
Handles cursor related code. To be honest, it’s rarely used at work, so I won’t go into it here.
jdbc
包
Generate jDBC-capable statements.
Lang package
Annotations that specify whether Java7 or Java8 apis are used.
conclusion
In the face of how to look at the source code, a lot of people are unable to start, some people are also messing around, to the end of the affirmation to see a little bit to give up.
For look at the source routine personal advice:
1 learn to use, must be skilled in use.
2. Master some common design patterns (factory mode, single column mode, template method mode, decorator mode, proxy mode, etc.).
3. Familiar with design principles.
4. Familiarize yourself with the package directory of the source code and the general functionality of each package.
5. Think about why this is so.
6. King Mode: Now that you know how to use it, how would you design it?