Recently, I am on paternity leave, so I am going to read two books, one is “MyBatis: Technical Principles and Practices” and the other is “RabbitMQ Practical: Efficient Deployment of Distributed Message Queues”. In order to deepen my memory and understanding, I will organize, expand and record them.

The goal of reading a book is not to remember all the details, but to get an overall understanding of what a technology can do, its features, basic modules, implementation principles, and common usage scenarios.

This article shares MyBatis the first book, first recall the related concepts of JDBC, understand the most basic way to access the database provided by Java, and then introduce the basic features and core components of MyBatis, finally said the overall structure of the book, understand the general content of the following articles.

JDBC Related Concepts

Java programs are connected to the database through JDBC, database programming through SQL, JDBC is a series of specifications proposed by SUN Company, only defined the interface specification, the specific implementation by each database manufacturers to achieve, it is a typical bridge mode.

The bridge pattern is a structural design pattern characterized by the separation of abstraction from the implementation of behavior, the definition of interfaces separately, and the ability to maintain the independence of the parts and extend their functionality.

The JDBC specification

A standard interface is defined and abstracted as follows: Connection is used to represent a Connection to a database, Statement is used to execute SQL, and ResultSet is used to represent the results returned by SQL, providing convenience for data. From a Connection, you can create a Statement that executes a query to obtain a ResultSet.

The Connection, Statement, and ResultSet mentioned above should all be interfaces that are implemented by each database provider. With the specification, you can access a variety of types of databases through a unified interface, and you can switch the database at will.

Database-driven

As mentioned above, the implementation of the interface is provided by different vendors, so the class name of the implementation class is not uniform. When creating a Connection object, the code will die of one of the implementation classes, and when switching databases, the code will need to be changed, which is not good. To solve this problem, the concept of Driver is abstracted.

Connection con=MySqlConnectionImpl("127.0.0.1".3306."mi_user",userName,pwd);
Copy the code

Each database needs to implement a Driver interface. A database Connection can be obtained through the Driver and dynamically created through the reflection mechanism.

Class.forName("com.mysql.jdbc.Drier");
Copy the code

The same program may access different databases and manage drivers through DriverManager. Drivers need to be registered with DriverManager when they are initialized.

DriverManager provides a getConnection method to establish a database Connection:

Connection con=DriverManager.getConnection("127.0.0.1".3306."mi_user",userName,pwd);
Copy the code

If there are multiple database drivers, DriverManager should be specified in the database connection URL. For example, mysql needs to add JDBC :mysql prefix:

String url= "JDBC: mysql: / / 127.0.0.1:3306 / mi_user";
Connection con=DriverManager.getConnection(url,userName,pwd)
Copy the code
The data source

A DataSource DataSource contains two parts, the connection pool and the connection pool management, which is conventionally called the connection pool. During system initialization, the database connection is stored in memory as an object, and when the database needs to be accessed, an established free connection object is retrieved from the connection pool.

Use a DataSource, obtain its DataSource object, and dynamically obtain a database connection through this object. In addition, a DataSource object can be registered with a Name service (JNDI), through which the DataSource object can be obtained without a hard coded driver.

DriverManager is provided by JDBC1, and DataSource is a new feature of JDBC2 that provides a better way to connect to data sources.

Compare Hibernate and MyBatis

Through the above introduction, the traditional JDBC programming has brought us the function of connecting to the database, but its workload is relatively large, first connect, then deal with the UNDERLYING JDBC transactions, processing data types, but also may produce exceptions to capture processing and the correct closure of resources.

In practice, JDBC programming is rarely used. ORM model is proposed to solve the mapping between database data and POJO objects.

Hibernate and Mybatis are BOTH ORM models. Hibernate provides a full table mapping model, which has a high degree of encapsulation for JDBC. Hibernate also has a number of disadvantages, as listed below:

  • The inconvenience of full table mapping, such as the need to send all fields when updating;
  • Unable to assemble different SQL for different conditions;
  • Poor support for multi-table associations and complex SQL queries. You need to write your own SQL, and after returning, you need to assemble the data into POJOs.
  • Stored procedures are not supported effectively;
  • Although HQL exists, the performance is poor, and large Internet systems often need to optimize SQL, which Hibernate cannot do.

In the large Internet environment, flexible, SQL optimization, reduce the transfer of data is the most basic optimization method, Hibernate can not meet the requirements, and MyBatis offers you flexible, convenient way, is a semi-automatic mapping framework.

MyBatis needs to manually match to provide POJOs, SQL, and mappings, while Hibernate for full table mapping only needs to provide POJOs and mappings.

MyBatis can configure dynamic SQL. It can solve the problem of Hibernate table names changing according to time and different conditions. SQL can be optimized, SQL mapping rules can be determined by configuration, and stored procedures can be supported, which is more convenient for some complex SQL queries that require performance optimization.

Core components

Core components include the following:

  • SqlSessionFactoryBuilder: Generates an SqlSessionFactory based on configuration information or code;
  • SqlSessionFactory: relies on the factory to generate SqlSession;
  • SqlSession: an interface that can either send SQL to execute and return results, or obtain Mapper;
  • SQL Mapper is a newly designed component of MyBatis, which is composed of a Java interface and XML file. It needs to give the corresponding SQL and mapping rules. It sends the SQL for execution and returns the results.
Build a SqlSessionFactory

Each MyBatis application is centered on an instance of SqlSessionFactory whose task is to create a SqlSession. SqlSesion is similar to a JDBC Connection object.

There are two ways to create an SqlSessionFactory: one is XML configuration, and the other is code. The XML configuration is recommended.

Define the mybatis-config. XML file as follows:

<? xml version="1.0" encoding="UTF-8"? >

      

<configuration>
 <properties resource="application.properties">
 </properties>
 
 <! -- define aliases -->
 <typeAliases>
 <typeAlias alias="role" type="com.learn.chapter2.po.Role"/>
 </typeAliases>
 
 <! -- Define database information. The default build environment is to use the Development database -->
 <environments default="development">
    <environment id="development">
    <! -- Using JDBC transaction Management -->
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        </dataSource>
    </environment>
 </environments>
 
 <! -- Define mapper -->
 <mappers>
 <mapper resource="com\learn\chapter2\mapper\roleMapper.xml"/>
 </mappers>
</configuration>
Copy the code

Create a SqlSessionFactory

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Copy the code
Create a SqlSession

SqlSession is an interface class that acts as a facade while the Executor interface does the real work. You need to make sure you close it properly every time you run out of it.

SqlSession sqlSession=null;
try{
    sqlSession=sqlSessionFactory.openSession();
    //some code
    sqlSession.commit();
} catch(Exception ex){
    sqlSession.roolback();
} finally{
    if(sqlSession! =null){ sqlSession.close(); }}Copy the code
mapper

A mapper is a combination of Java interfaces and XML files (or annotations) that do the following:

  • Defining parameter Types
  • Describe the cache
  • Describing SQL Statements
  • Define the mapping between query results and POJOs

First, define the Java interface:

public interface RoleMapper{
    public Role getRole(Long id);
}
Copy the code

Next, define the mapping XML file, roleMapper.xml

<? xml version="1.0" encoding="UTF-8"? >

      
 
 <mapper namespace ="com.learn.chapter2.mapper.RoleMapper">
    <select id="getRole" paramterType="long" resultType="role" >
        select id,role_name as roleName , note from t_role where id=#{id}
    </select>
 </mapper>
Copy the code

The POJO object Role is a simple definition and will not be listed. #{id} is the parameter of this SQL statement, and the alias of the SQL column is the same as the name of the POJO attribute. The query result of this statement is automatically mapped to the Role attribute, which is automatic mapping.

Execute the query

RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);
Role role=roleMapper.getRole(1L);
String roleName=role.getRoleName();
Copy the code
Component life cycle

SqlSessionFactory In the whole life cycle of MyBatis application, each database only corresponds to a SqlSessionFactory, can implement a tool class, to obtain the object in singleton mode.

The lifecycle of the SqlSession is a thread-unsafe object during the request to the database to process a transaction, so be careful when multiple threads are involved. It survives the requests and operations of an application and can execute multiple SQL entries to ensure transaction consistency.

Mapper is used to send SQL and then return the desired result, or execute SQL to modify database data, so it should be within a SqlSession transaction method, just like the execution of an SQL statement in JDBC, and its maximum scope is the same as SqlSession.

The overall structure of the book

This book is divided into three parts, which successively introduces the basic application, principle, plug-in development and actual application of MyBatis.

The base application

How to use MyBatis efficiently

  • MyBatis features
  • Core components and their lifecycle
  • MyBatis configuration
  • mapper
  • Dynamic SQL
MyBatis principle

In-depth source code to understand the internal operation principle of MyBatis and plug-in development methods and skills:

  • Introduction to the parsing and running principle of MyBatis, will understand the construction method of SqlSession, and how the four objects work
  • Introduction to MyBatis plug-ins
Practical application

MyBatis (MyBatis)

  • How to integrate MyBatis in Spring project
  • This paper introduces the practical scenarios of MyBatis, selects some typical scenarios, and analyzes some errors and performance losses that developers need to pay attention to avoid in each scenario

The next section will introduce the related configuration of MyBatis, better configuration of MyBatis to apply to different business scenarios, as well as the extension provided to us.

Please scan the qr code below and follow my wechat official account ~