Mybatis persistence layer framework functional architecture and underlying analysis

“This is the 26th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

About the author

  • The authors introduce

🍓 Blog home Page: author home page 🍓 Introduction: High-quality creator in the JAVA field 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors 🍓, Ali Cloud expert blogger, 51CTO expert blogger, follow me: Pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻


This article will introduce myBatis persistence layer framework from the operation principle of MyBatis, the creation of SqlSessionFactory, the creation of READING XML file and Spring hosting, the life cycle of myBatis related elements.

Environmental requirements:

  • JDK1.8 above
  • MySQL5.5 above
  • Maven3.5 above
  • The IDEA or the Eclipse

Preparation before learning:

  • JDBC
  • MySQL
  • Maven
  • Junit

1, Mybatis overview

1.1. What is MyBatis

MyBatis is a ** Apache open source project iBatis**. In 2010, the project was migrated from apache Software Foundation to Google Code, hosted by Google, and renamed MyBatis. Migrated to Github in November 2013.

The term iBATIS comes from a combination of “Internet” and “Abatis” and is a Java-based persistence layer framework. IBATIS provides persistence layer frameworks including SQL Maps and Data Access Objects (DAO)

  • MyBatis is an excellent persistence layer framework that supports ordinary SQL queries, stored procedures, and advanced mapping.
  • MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval encapsulation of result sets.
  • MyBatis can use simple XML formats or annotations for configuration and raw mapping to map interfaces and Java’s POJOs (Plain Old Java Objects) to records in the database.

Mybatis official documentation: www.mybatis.org/mybatis-3/z…

Making: github.com/mybatis/myb…

1.2, characteristics

1. Simple and easy to learn: Small and simple in itself. Without any third party dependence, the simplest installation as long as two JAR files + configuration several SQL mapping files easy to learn, easy to use, through the documentation and source code, can be more fully grasp its design ideas and implementation.

2. Flexibility: MyBatis does not impose any impact on the existing design of the application or database. SQL is written in XML for unified management and optimization. All requirements for operating a database can be met through SQL statements.

3. Remove the coupling between SQL and program code: by providing DAO layer, the business logic and data access logic are separated, making the system design clearer, easier to maintain and easier to unit test. Separation of SQL and code improves maintainability.

4. Provide mapping labels to support orM field relational mapping between objects and databases

5, provide object relationship mapping label, support object relationship maintenance

6, provide XML tags, support the preparation of dynamic SQL.

1.3. Persistence

  • Persistence is a mechanism for converting program data between persistent and transient states.
    • That is, data (such as objects in memory) is saved to a permanent storage device (such as a disk). The main application of persistence is to store objects in memory in a database, in disk files, XML data files, and so on.
    • JDBC is a persistence mechanism. File IO is also a persistence mechanism.
    • In life: refrigerate fresh meat and defrost it when eating. The same goes for canning fruit.
  • Why do YOU need a persistence service? That’s due to a defect in memory itself
    • Data can be lost after a power outage, but there are certain objects, such as bank accounts, that should not be lost at all costs. Unfortunately, there is no guarantee that memory will never fail.
    • Memory is too expensive, compared with hard disk, CD and other external storage, the price of memory is 2~3 orders of magnitude higher, and maintenance costs are high, at least always need to power it. Therefore, even if the object does not need to be stored permanently, it will not be able to stay in memory due to the capacity limitation of memory, and will need to be persisted to cache to external memory.

1.4. Persistence Layer

What is the persistence layer?

  • —-> DAO layer [DAO (Data Access Object) Data Access Object] also known as mapper
  • In most cases, especially in enterprise applications, data persistence often means storing data in memory on disk for curing, and the implementation process of persistence is mostly done through various relational databases.
  • But there is one word that needs to be stressed, and that is “layer”. Data persistence is an essential part of most application systems. So we have a built-in persistence layer in our system, right? Maybe, but maybe that’s not the case. The reason why the concept of “persistence layer” should be developed independently, instead of “persistence module” and “persistence unit”, means that there should be a relatively independent logical level in our system architecture, focusing on the realization of data persistence logic.
  • This layer should have a clear and rigid logical boundary relative to the rest of the system. In other words, it is used to operate the database!

1.5. Why do I need Mybatis?

  • Mybatis is an application for storing and retrieving data from a database
  • Traditional JDBC operations have a lot of repetitive code blocks. For example: data out of the package, the establishment of the database connection and so on… The framework can reduce repeated code and improve development efficiency
  • MyBatis is a semi-automated ORM framework (Object Relationship Mapping)
  • All things, without Mybatis can still do, just use it, all implementation will be more simple! There is no higher or lower technology, only the person who uses it

2. Functional architecture and underlying principles

2.1. Functional architecture

The functional architecture of Mybatis is divided into three layers

  1. API Interface layer: Interface apis for external use by developers to manipulate the database through these native apis. As soon as the interface layer receives the call request, it calls the data processing layer to complete the specific data processing.

  2. Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation based on the request of the call.

  3. Base support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache handling, all of which are common and extracted as the most basic components. It provides the most basic support for the upper data processing layer.

Here may not be very clear words, with a figure to show the image to you.

2.2 review JDBC programs

JDBC Programming Steps

1. Load the database driver

2. Create and get database links

Create a JDBC Statement object

4. Set the SQL statement

Set parameters in SQL statement (preparedStatement)

6. Execute the SQL statement and obtain the result

7. Analyze the SQL execution results

Release resources (resultSet, preparedStatement, Connection)

There are many problems with JDBC

1. Frequent creation and release of database links waste system resources and thus affect system performance. This problem can be solved by using database link pools.

2, Sql statement in the code hard coding, resulting in code is not easy to maintain, the actual application of Sql changes may be large, Sql changes need to change the Java code.

3. There is hard coding in transferring parameters to possession bit symbols in preparedStatement, because the WHERE conditions of SQL statements are not necessarily, which may be more or less, and it is difficult to maintain the system by modifying SQL and modifying the code.

4, there is hard coding (query column name) for result set parsing, SQL changes lead to parsing code changes, the system is not easy to maintain, if the database records can be encapsulated into POJO object parsing is more convenient.

2.3 Operation principle

MyBatis as a framework of persistence layer, its main idea is to strip out a large number of SQL statements in the program and configure them in the configuration file to achieve flexible configuration of SQL. This has the advantage of separating the SQL from the program code, allowing you to modify the SQL directly in the configuration file without modifying the program code.

  1. Load the configuration: The configuration comes from two places, one is a configuration file, the other is a Java code annotation. Load the SQL configuration information into one MappedStatement object (including the incoming parameter mapping configuration, the executed SQL statement, and the result mapping configuration) and store it in memory.
  2. SQL parsing: Mybatis will find the corresponding MappedStatement based on the ID of the SQL and the object (which can be a Map, JavaBean or basic data type). The MappedStatement is then parsed against the incoming parameter object to obtain the SQL statement and parameters to be executed.
  3. SQL execution: the final SQL and parameters to the database for execution, the operation of the database results.
  4. Result mapping: Transforms the result of operating on a database according to the configuration of the map, either to a HashMap, JavaBean, or primitive data type, and returns the final result.

2.4 General process of Mybatis operation

  1. Loading the configuration and initializing the triggering conditions: Loading the configuration file Process: Load the SQL configuration information into one MappedStatement object (including the incoming parameter mapping configuration, executed SQL statements, and result mapping configuration) and store it in memory.
  2. Receive call request trigger condition: call API provided by Mybatis pass in parameter: ID for SQL and pass in parameter object processing process: pass the request to the lower request processing layer for processing.
  3. Processing operation requestThe trigger conditionThe API layer passes the requestIncoming parameters: is the ID of the SQL and the incoming parameter objectThe process:
    • Locate the MappedStatement object based on the SQL ID.
    • The MappedStatement object is parsed against the passed parameter object to get the SQL to execute and execute the passed parameter.
    • Get the database connection, execute to the database based on the resulting final SQL statement and execute the incoming parameters, and get the execution results.
    • The resulting execution result is transformed according to the result mapping configuration in the MappedStatement object and the final processing result is obtained.
    • Release the connection resource.
  4. Return Processing result Returns the final processing result.

After the language

The original intention of the director to write blog is very simple, I hope everyone in the process of learning less detours, learn more things, to their own help to leave your praise 👍 or pay attention to ➕ are the biggest support for me, your attention and praise to the director every day more power.

If you don’t understand one part of the article, you can reply to me in the comment section. Let’s discuss, learn and progress together!