MySQL installation and startup

Installing and starting a relational data is the basis for debugging MyBatis source code. At present, many Internet companies will be MySQL as the preferred database, so here I also choose MySQL database to match the debugging of MyBatis source code.

1. Download the MySQL

First, download the latest version of MySQL Community Server from the MySQL official website. MySQL Community Server is the Community version of MySQL Server and is available for free trial. Here, I choose tar.gz for installation, so you need to download the corresponding tar.gz installation package, as shown in the red box below:

2. Configure the MySQL

After downloading the tar.gz installation package, I can run the following command to decompress the tar.gz package to obtain the mysql-8.0.26-macos11-x86_64 directory.

The tar ZXF mysql - 8.0.26 - macos11 - x86_64. Tar. GzCopy the code

Then run the following command to go to the support-files directory:

cd. / mysql - 8.0.26 - macos11 - x86_64 / support - filesCopy the code

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

vim mysql.server
Copy the code

Here I need to set the basedir and datadir variables to the root directory of MySQL and the data directory of MySQL respectively (as shown in the following figure), and then run the :wq command to save the changes of mysql.server and exit.

3. Start the MySQL

MySQL > select bin from MySQL;

cd ../bin/
Copy the code

The basedir and datadir parameters can be used to specify the root directory and data directory.

. / mysqld - the initialize - user = root - basedir = / Users/XXX/Downloads/mysql - 8.0.26 macos11 -- x86_64 - the datadir = / Users/XXX/Downloads/mysql - 8.0.26 macos11 - x86_64 / dataCopy the code

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

With this 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/
Copy the code

Then run the following command to start the MySQL service:

./mysql.server start
Copy the code

After the MySQL service starts normally, you should see output like the following:

4. Log in to MySQL

Next jump to the bin directory:

cd ../bin/

Copy the code

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

./mysql -uroot -p'rAUhw9e&VPCs'
Copy the code

After login, you can enter MySQL Shell, as shown below:

Then I can change the password in MySQL Shell as follows:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'New password';
Copy the code

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

To stop the MySQL service, go to the support-files directory and run the following command:

cd ../support-files/

./mysql.server stop
Copy the code

It should also be noted that in the actual development process, the graphical interface client of MySQL, such as Navicat and MySQL Workbench Community Edition, is generally used only in the Linux command line of the machine online. To perform some operations directly using the MySQL Shell. Of course, I personally recommend using these GUI clients to improve your daily development efficiency.

MyBatis source code environment construction

After completing MySQL installation and startup, you can start to build MyBatis source environment.

First of all, you need to install the JDK, Maven, Git and other basic Java development environment, the installation of these software I will not expand here, you should be very familiar with.

To download MyBatis from GitHub, run the following command:

git clone https://github.com/mybatis/mybatis-3.git
Copy the code

To switch branches, run the following git command:

Git checkout -b mybatis-3.5.6Copy the code

Finally, I Open IDEA and select Open or Import to Import MyBatis source code, as shown in the picture below:

After the import is complete, you can see the source structure of MyBatis, as shown below:

MyBatis architecture introduction

After completing the construction of MyBatis source environment, I will take you to analyze the architecture of MyBatis.

MyBatis is divided into three layers, namely the basic support layer, core processing layer and interface layer, as shown in the figure below:

1. Foundation support layer

The foundation support layer is the foundation of the whole MyBatis framework, which provides very basic functions for the whole MyBatis framework. Each module provides a cohesive, single capability. According to these single capabilities, the MyBatis foundation support layer can be divided into nine foundation modules as shown in the figure above.

Because 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 information to understand and learn. I will briefly describe the basic functions of the remaining eight modules, and in the second module of this course, I will walk you through the implementation of these basic modules in detail.

First, the type conversion module. In the order system implementation shown last time, we can define an alias for a class in the mybatis-config.xml configuration file through the

tag. The “alias mechanism” used here is implemented by the type conversion module in the myBatis base support layer.

In addition to the “alias mechanism”, the type conversion module also implements the conversion between JDBC types and Java types in MyBatis. This function is reflected in the binding argument and mapping ResultSet scenarios:

  • In a scenario where SQL template binding users pass in arguments, the type conversion module converts Java type data to JDBC type data;
  • When mapping a ResultSet to a result object, the type conversion module converts JDBC type data to Java type data.

The specific situation is shown in the figure below:

Second, the log module. Log is the main clue source for troubleshooting problems, locating bugs and locking performance bottlenecks in our production practice. In any mature system, there will be a reasonable level and informative log module, and MyBatis is no exception. MyBatis provides a logging module to integrate third-party logging frameworks in the Java ecosystem, which can integrate Log4j, Log4j2, SLF4J and other excellent logging frameworks.

Third, reflection tool module. Reflection is very powerful in Java, and many open source frameworks rely on reflection to implement relatively flexible requirements, but most Java programmers rarely use reflection directly in their actual work. MyBatis reflection toolbox is a layer of encapsulation on the basis of Java reflection. It provides more flexible and convenient API interfaces for upper users. Meanwhile, it caches metadata related to Java’s native reflection, improves the efficiency of reflection code execution and optimizes the performance of reflection operation.

Fourth, the Binding module. In the example of the order system described in the previous lecture, we could obtain an agent for the Mapper interface through SqlSession, and then use this agent to perform database operations associated with the mapper.xml file. In this way, errors can be brought forward to compile time, which is done through the Binding module.

In particular, when using MyBatis, we do not need to write the specific implementation of Mapper interface, but use the Binding module to automatically generate dynamic proxy objects of Mapper interface. Some simple data operations can be completed directly in the Mapper interface using annotations, and even the mapper. XML configuration file does not need to be written. However, if the ResultSet mapping and dynamic SQL are very complex, it is recommended to maintain in the Mapper. XML configuration file will be more convenient.

Fifth, the data source module. One of the core components of persistence layer framework is data source, which can improve system performance exponentially. MyBatis itself provides a good data source implementation, which is the default implementation of MyBatis. In addition, in the Java ecology, there are many excellent open source data sources to choose from. The data source module of MyBatis also provides relevant interfaces to integrate with third-party data sources, which also provides users with more choice space and improves the flexibility of data source switching.

Sixth, cache module. Database is a very core storage in practice generation, and a lot of business data will be landed in the database, so the performance of the database directly affects the performance of the upper business system. Many of our online services are read more and write less. When the database encounters a bottleneck, caching is one of the most effective and commonly used methods (as shown in the following figure). The correct use of caching can intercept part of the database requests in the cache layer, which can reduce the pressure on part of the database and improve the system performance.

In addition to using external third-party caches such as Redis and Memcached, persistence frameworks generally have built-in caches. For example, MyBatis provides level 1 cache and level 2 cache, which are implemented in the cache module of the basic support layer.

Seventh, the parser module. In the previous example of the order system, we saw 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. These two files are parsed by the parser module of MyBatis, which mainly relies on XPath to realize efficient parsing of XML configuration files and various expressions.

Eighth, the transaction management module. The persistence layer framework generally provides a set of transaction management mechanism to achieve the transaction control of the database. MyBatis has carried out a simple abstraction of the transaction in the database, providing a simple and easy to use transaction interface and implementation. Typically, Java projects integrate with Spring and the Spring framework manages transactions. In later courses, I will also explain the principle of MyBatis integration with Spring in depth, including the integration related to transaction management.

2. Core processing layer

After introducing the basic support layer of MyBatis, we will 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 whole process of executing a SQL statement. Let me describe each part of the implementation in the core processing layer.

First, configuration parsing. MyBatis has three places to add configuration information: MyBatis -config. XML configuration file, mapper. XML configuration file, and annotation information in Mapper interface. During the initialization of MyBatis, the Configuration information is loaded and the parsed Configuration object is saved into the Configuration object.

For example, the

tag used in the order system example (that is, custom query result set mapping rules) is resolved into a resultMap object. We can use the resulting Configuration object to create an SqlSessionFactory object (the factory object that created the SqlSession object), which can then be created to perform database operations.

Second, SQL parsing and scripting modules. The biggest highlight of MyBatis should be its dynamic SQL function, just need to provide MyBatis tags can dynamically generate the actual execution of SQL statements according to the actual running conditions. MyBatis provides very rich dynamic SQL tags, including < WHERE > tags,

tags,

tags,

tags and so on.


The scripting module in MyBatis is the core module responsible for dynamically generating SQL. It parses the labels in dynamic SQL and forms an SQL template based on the arguments passed in by the run-time user. It then processes the placeholders in the SQL template and populates the placeholders with run-time arguments to get the SQL statements that the database can actually execute.

Third, SQL execution. To execute a SQL statement in MyBatis, there are many components. The core components are Executor, StatementHandler, ParameterHandler, and ResultSetHandler.

Executor calls the transaction management module for transaction control and manages level 1 and level 2 caches through the cache module. The actual execution of the SQL statement will be performed by StatementHandler. So how does that work? StatementHandler relies on ParameterHandler to bind SQL template arguments. The java.sql.Statement object sends SQL statements and bound arguments to the database for execution. Get the ResultSet from the database, and finally, the ResultSet is mapped into Java objects and returned to the caller by the ResultSet Andler, which is the core of the SQL execution module.

The following diagram shows the core process of executing an SQL statement in MyBatis:

Fourth, plug-ins. Many mature open source frameworks offer extensibility in a variety of ways. When the framework’s native capabilities are not sufficient for certain scenarios, plug-ins can be implemented for those scenarios to meet the requirements, so that the framework can have enough vitality. This is why the MyBatis plug-in interface exists.

At the same time, you can also use custom plugins to extend MyBatis, or change the default behavior of MyBatis. Since plugins affect the behavior of the MyBatis kernel, it is important to understand the internal workings of MyBatis before you customize your plugins to avoid writing undesired plugins, introducing weird functional bugs or performance issues.

3. The interface layer

The interface layer is the set of interfaces exposed to call by MyBatis. These interfaces are some of the most commonly used interfaces when using MyBatis, such as SqlSession interface, SqlSessionFactory interface, etc. Among them, the most core is the SqlSession interface, you can achieve a lot of functions through it, for example, get Mapper agent, execute SQL statements, control transaction switch and so on.