-MyBatis source code environment construction and overall architecture analysis

Last time, I demonstrated the basic use of MyBatis in practical projects through an example of the order system to help you quickly get started using the MyBatis framework. This time, I will take you to build a debugging environment for MyBatis source code, and analyze the source code structure of MyBatis for you. These are paving the way for the source code analysis later.

MySQL installation and startup
Installing and starting a relational data is the basis for debugging the MyBatis source code. At present, many Internet companies regard MySQL as the preferred database, so here I also choose MySQL database to debug the MyBatis source code

  1. Download MySQL
    First, download the latest version of MySQL Community Server from the MySQL official website. MySQL Community Server is a community version of MySQL server, you can try it for free. Here I choose to use tar.gz to install, so I need to download the corresponding tar.gz installation package, as shown in the red box in the following figure:
    Insert picture description here
    MySQL download interface
  2. After configuring MySQL to
    download the tar.gz installation package, I execute the following command to decompress the tar.gz package and get the mysql-8.0.22-macos10.15-x86_64 directory.
tar -zxf mysql-8.0.22-macos10.15-x86_64.tar.gz

Then execute the following command to enter the support-files directory:

cd ./mysql-8.0.22-macos10.15-x86_64/support-files

Execute the following command to open the mysql.server file for editing:

vim mysql.server

Here I need to set the basedir and datadir variables to the root directory of MySQL and the data directory under the MySQL directory (as shown in the figure below), and finally execute the :wq command to save the changes to mysql.server and exit.
Insert picture description here
mysql.server file modification example Figure
3. After starting MySQL
, I executed the following command to enter the MySQL bin directory:

cd ../bin/

And execute the following mysqld command to initialize MySQL, but you need to pay attention to the parameter information added here, you can specify the root directory and data directory through the basedir and datadir parameters.

./mysqld --initialize --user=root --basedir=/Users/xxx/Downloads/mysql-8.0.22-macos10.15-x86_64 --datadir=/Users/xxx/Downloads/mysql-8.0.22-macos10.15-x86_64/data

After the initialization process is completed normally, you can get the initial default password of MySQL in the command line, as shown in the following figure:

Insert picture description here
Example image of successfully initializing MySQL
With the default password, I can start and log in to the MySQL service. First, I need to jump to the support-files directory:

cd ../support-files/

Then execute the following command to start the MySQL service:

./mysql.server start

After the MySQL service is started normally, you can see the output as shown in the following figure:
Insert picture description here
Example of successfully starting MySQL Figure
4. Log in to MySQL and
then jump to the bin directory:

cd ../bin/

And execute the following command to log in to MySQL using the default password obtained earlier.

./mysql -uroot -p'rAUhw9e&VPCs'

After logging in, you can enter MySQL Shell, as shown in the following figure:
Insert picture description here
Example of successful login to MySQL
Then I can change the password in MySQL Shell, the specific commands are as follows:

ALTER USER 'root'@'localhost' IDENTIFIED BY '新密码';

After the execution is successful, the next time you use MySQL Shell to connect, you will need to log in with the new password.

Finally, if you want to close the MySQL service, you can jump to the support-files directory and execute the following command:

cd ../support-files/

./mysql.server stop

If you get the following output, it means that the MySQL service has been successfully shut down:
Insert picture description here
Sample diagram of MySQL successfully shutting down

It should also be noted here that in the actual development process, MySQL graphical interface clients are generally used, such as Navicat, MySQL Workbench Community Edition, etc. Generally, MySQL will only be used directly on the Linux command line of the online machine. Shell performs some operations.

Of course, I personally recommend you to use these graphical interface clients, which can improve your daily development efficiency.
MyBatis source code environment construction
After completing the installation and startup of MySQL, you can start to build the MyBatis source code environment.

First of all, you need to install the basic environment for Java development such as JDK, Maven, and Git. The installation of these software will not be introduced here. You should already be very familiar with it.

Next, execute the following command to download the source code of MyBatis from GitHub:

git clone https://github.com/mybatis/mybatis-3.git

Depending on the network speed, the time-consuming process of this downloading process will vary. After the download is complete, you can get the following output:
Insert picture description here
MyBatis download example diagram
At this point, I got a mybatis-3 directory locally, and I can enter the directory by executing the following cd command:

cd ./mybatis-3/

Then execute the following git command to switch branches (this course is based on the code of MyBatis 3.5.6 version for analysis):

git checkout -b mybatis-3.5.6 mybatis-3.5.6

After the switch is completed, I can also use the following git command to check whether the branch switch is successful:

git branch -vv

Here I get the output as shown in the figure below, which means I have switched to mybatis-3.5.6 tag.
Insert picture description here
git branch example diagram

Finally, I open IDEA, select Open or Import, and import the MyBatis source code, as shown in the following figure:
Insert picture description here
IDEA import option diagram After the
import is completed, you can see the source code structure of MyBatis, as shown in the following figure:
Insert picture description here
Introduction to MyBatis architecture
completes the MyBatis source environment setup After that, I will take you to analyze the architecture of MyBatis.

MyBatis is divided into three layers of architecture, namely the basic support layer, core processing layer and interface layer, as shown in the following figure:
Insert picture description here

  1. Basic support layer The
    basic support layer is the foundation of the entire MyBatis framework. It provides very basic functions for the entire MyBatis framework. Each module provides a cohesive and single capability. The MyBatis basic support layer can be based on these single capabilities. Divided into nine basic modules as shown in the figure above.

Since the function of the resource loading module is very simple and the frequency of use is not high, I will not introduce it here. If you are interested, you can refer to the relevant materials to understand and learn. Below I will briefly describe the basic functions of the remaining eight modules. In the second module of this course, I will take you to analyze the specific implementation of these basic modules in detail.

The first one is the type conversion module. In the order system implementation shown in the previous lecture, we can define an alias for a class through tags in the mybatis-config.xml configuration file. The "alias mechanism" used here is the type conversion module in the basic support layer of MyBatis Achieved.

In addition to the "alias mechanism", the type conversion module also implements the mutual conversion between the JDBC type and the Java type in MyBatis. This function is reflected in the scenarios of binding actual parameters and mapping ResultSet:

In the scenario where the SQL template binds the user to pass in the actual parameters, the type conversion module converts Java type data into JDBC type data;

When mapping the ResultSet to the result object, the type conversion module converts JDBC type data into Java type data.

The specific situation is shown in the figure below: The
Insert picture description here
second one is the log module. Logs are the main source of clues for troubleshooting, locating bugs, and locking performance bottlenecks in our production practice. In any mature system, there will be log modules with reasonable levels and full information, and MyBatis is no exception. MyBatis provides a logging module to integrate third-party logging frameworks in the Java ecosystem. This module can currently integrate excellent logging frameworks such as Log4j, Log4j2, and slf4j.

The third one is the reflection tool module. The reflection function in Java is very powerful. Many open source frameworks rely on reflection to achieve some relatively flexible requirements, but most Java programmers rarely use reflection technology directly in their actual work. The reflection toolbox of MyBatis is a layer of encapsulation based on Java reflection, providing a more flexible and convenient API interface for upper users, and at the same time caching metadata related to Java's native reflection, which improves the efficiency of reflection code execution , Optimize the performance of reflection operation.

The fourth is the Binding module. In the order system example introduced in the previous lecture, we can obtain the proxy of the Mapper interface through SqlSession, and then perform the database operations in the associated Mapper.xml file through this proxy. In this way, some errors can be advanced to the compile time, and this function is completed by the Binding module.

It is specifically stated here that when using MyBatis, we do not need to write a specific implementation of the Mapper interface, but use the Binding module to automatically generate a dynamic proxy object for the Mapper interface. For some simple data operations, we can also use annotations directly in the Mapper interface. Even the Mapper.xml configuration file does not need to be written, but if the ResultSet mapping and dynamic SQL are very complicated, it is recommended to maintain it in the Mapper.xml configuration file. Convenience.

The fifth is the data source module. One of the core components of the persistence layer framework is the data source. A data source with outstanding performance can double the performance of the system. MyBatis itself provides a set of good data source implementations, which is also the default implementation of MyBatis. In addition, in the Java ecosystem, there are many excellent open source data sources to choose from. The data source module of MyBatis also provides related interfaces for integration with third-party data sources, which also provides users with more choices. Improved the flexibility of data source switching.

The sixth is the cache module. The database is a very core storage in practice generation, and many business data will fall into the database, so the quality of the database performance directly affects the quality of the upper-level business system. Many of our online businesses are in the scenario of reading more and writing less. When the database encounters a bottleneck, caching is one of the most effective and commonly used methods (as shown in the figure below). The correct use of caching can intercept some database requests in the cache. At this level, this can reduce the pressure on a part of the database and improve system performance.
Insert picture description here
In addition to using external third-party caches such as Redis and Memcached, persistence frameworks generally also come with built-in caches. For example, MyBatis provides first-level and second-level caches. The specific implementation is located in the cache module of the basic support layer. .

Seventh, the parser module. In the order system example in the previous lecture, we can see that there are two major configuration files in MyBatis that need to be parsed, one is the mybatis-config.xml configuration file, and the other is the Mapper.xml configuration file. Both of these files are parsed by the parser module of MyBatis, which mainly relies on XPath to achieve efficient parsing of XML configuration files and various expressions.

The eighth, transaction management module. The persistence layer framework generally provides a set of transaction management mechanisms to implement database transaction control. MyBatis provides a simple abstraction of transactions in the database and provides simple and easy-to-use transaction interfaces and implementations. Under normal circumstances, Java projects will be integrated with Spring, and the Spring framework will manage the affairs. In later courses, I will also explain in depth the principles of MyBatis and Spring integration, including transaction management-related integration.

  1. Core processing layer After
    introducing the basic support layer of MyBatis, let's analyze the core processing layer of MyBatis.

The core processing layer is the core implementation of MyBatis, which involves the initialization of MyBatis and the entire process of executing a SQL statement. Below I will introduce the implementation of each part of the core processing layer.

The first one is configuration analysis. We know that MyBatis has three places where you can add configuration information, namely: mybatis-config.xml configuration file, Mapper.xml configuration file, and annotation information in the Mapper interface. During the initialization of MyBatis, the configuration information will be loaded, and the configuration object obtained after parsing will be saved in the Configuration object.

For example, the tags used in the order system example (that is, the custom query result set mapping rules) will be parsed into ResultMap objects. We can use the obtained Configuration object to create the SqlSessionFactory object (that is, the factory object that creates the SqlSession object), and then create the SqlSession object to perform database operations.

The second one is the SQL parsing and scripting module. The biggest highlight of MyBatis should be its dynamic SQL function. You only need to use the tags provided by MyBatis to dynamically generate the actual executed SQL statements according to the actual operating conditions. The dynamic SQL tags provided by MyBatis are very rich, including tags, tags, tags, tags, etc.

The scripting module in MyBatis is the core module responsible for dynamically generating SQL. It will parse the tags in the dynamic SQL according to the actual parameters passed by the user at runtime, and form a SQL template, then process the placeholders in the SQL template, fill the placeholders with the actual parameters at runtime, and get the database to be truly executable SQL statement.

The third one is SQL execution. In MyBatis, to execute a SQL statement, a lot of components are involved, the core ones are: Executor, StatementHandler, ParameterHandler and ResultSetHandler.

Among them, the Executor will call the transaction management module to implement transaction related control, and at the same time will manage the first-level cache and the second-level cache through the cache module. The actual execution of the SQL statement will be implemented by the StatementHandler. How exactly is it done? StatementHandler will first rely on ParameterHandler to bind the actual parameters of the SQL template, then the java.sql.Statement object will pass the SQL statement and the bound actual parameters to the database for execution, get the ResultSet from the database, and finally, the ResultSetHandler will bind the ResultSet Mapped into Java objects and returned to the caller, this is the core of the SQL execution module.

The following figure shows the core process of MyBatis executing a SQL statement:

Insert picture description here
The fourth one is the plug-in. Many mature open source frameworks provide expansion capabilities in various ways. When the framework's native capabilities cannot meet certain scenarios, some plug-ins can be implemented for these scenarios to meet the needs, so that the framework can have sufficient vitality. This is also the meaning of the MyBatis plug-in interface.

At the same time, in actual application, you can also extend MyBatis through custom plug-ins, or change the default behavior of MyBatis. Because plug-ins can affect the behavior of the MyBatis kernel, before customizing the plug-ins, you must understand the internal operating principles of MyBatis to avoid writing plug-ins that do not meet expectations, introducing some weird functional bugs or performance problems.

  1. Interface layer The
    interface layer is a collection of interfaces exposed to calls by MyBatis. These interfaces are some of the most commonly used interfaces when using MyBatis, for example, the SqlSession interface, the SqlSessionFactory interface, and so on. Among them, the most core is the SqlSession interface, through which you can achieve many functions, such as obtaining Mapper agents, executing SQL statements, and controlling transaction switches.

Guess you like

Origin blog.csdn.net/Rinvay_Cui/article/details/113833353