banner
bladedragon

bladedragon

Basic features of MyBatis and principles of SqlSession

title: Basic Features of MyBatis and the Principle of SqlSession
date: 2020-01-20 19:09:53
tags: ["database", "framework"]
categories: Technical Exploration

Mainly summarize the basic configuration and basic features of MyBatis, and finally analyze the principle of SqlSession to understand the running process.

Introduction to Simple Configuration#

Simply put, the configuration of MyBatis can be divided into the following steps:

  • Write POJO or JavaBean, the ultimate goal is to map the query results from the database to JavaBean;
  • Configure the Mapper interface corresponding to the POJO: it contains various methods corresponding to the query statements in the mapper.xml;
  • Configure the XML mapping corresponding to the POJO: write cache, SQL query, etc.;
  • Configure the main MyBatis configuration file mybatis-config.xml: configure data source, scan mapper.xml, etc.

Note: The above configurations do not have strict order;

Using a clear configuration flowchart as an example:

image

It can be seen that the implementation class of the mapper interface is obtained through mybatis-config.xml -> SqlSessionFactoryBuilder -> SqlSessionFactory -> SqlSession -> mapper

Lifecycle#

  1. SqlSessionFactoryBuilder: Its role is to create a builder. Once the SqlSessionFactory is created, its task is considered complete and can be recycled.
  2. SqlSessionFactory: Its role is to create SqlSession, and SqlSession is equivalent to a Connection object in JDBC. Every time the application needs to access the database, we need to create a SqlSession through SqlSessionFactory. Therefore, SqlSessionFactory exists in the entire lifecycle of MyBatis (each database corresponds to a SqlSessionFactory, which is generated as a singleton).
  3. SqlSession: The lifecycle exists in the process of requesting database processing transactions, and it is a thread-unsafe object (in the case of multi-threading, special attention is required). It exists in the requests and applications of an application and can execute multiple SQL statements to ensure transaction consistency.
  4. Mapper: It is an interface and does not have an implementation class. Its role is to send SQL and return the results we need, or send SQL to modify the database table. Therefore, it exists in a SqlSession and is something at the method level. When the SqlSession is destroyed, the Mapper will also be destroyed.

Basic Features#

Lazy Loading#

Lazy loading means that the system delays the execution of the query. It is generally used for nested queries. The nested SQL query will be lazily loaded and will not be loaded until it is really needed. Just like a lazy person, you say something to him, he won't move until he needs to, so this feature is also called lazy loading.

Lazy loading must be configured in config.xml and can only be implemented through association or collection, after all, lazy loading is only needed in business scenarios where there is a mapping relationship.

Configuration statement:

<settings>       
    <setting name="lazyLoadingEnabled" value="true"/>       <setting name="aggressiveLazyLoading" value="false"/>  
</settings>

When using lazy loading, it is necessary to note that lazy loading must use resultMap, and resultType does not have lazy loading function.

Level One Cache#

  • Enabled by default, the cache scope is a SqlSession
  • Only the same query under one SqlSession will apply the cache. Even if the query is the same under different SqlSessions, the level one cache will not take effect.

Level Two Cache#

  • Solve the problem of isolation between SqlSession, and the cache scope is a Mapper interface.

  • The level two cache is not enabled by default and needs to be configured. MyBatis requires that the returned POJO must be serializable, that is, the POJO implements the Serializable interface.

  • The cache configuration only needs to be <cache/> in the XML configuration, or specify the algorithm, refresh interval, cache status, size, etc.

    Example:

image

  • All select statements in the mapping statement file will be cached;
  • All insert, update, and delete statements in the mapping statement file will refresh the cache;
  • The cache uses the default LRU (Least Recently Used) algorithm for recycling;
  • According to the timetable, the cache will not be refreshed in any time order;
  • The cache will store 1024 references to list collections or objects;
  • The cache is considered a read/write cache, which means it cannot be shared, but it can be safely modified.

Custom Cache#

Implementing interfaces provided by MyBatis using Redis or other caching mechanisms.

Practical Configuration#

To be supplemented

Principle of SqlSession#

SqlSession provides select/insert/update/delete methods.

The mapper is actually a dynamic proxy object. By entering the execute method of MapperMethod, you can easily find the deletion, update, query, and selection methods of SqlSession.

From the bottom-up implementation: By using dynamic proxy technology, let the interface run, then use the command pattern, and finally use the interface methods of SqlSession (getMapper() method, etc. to get Mapper) to execute SQL queries (that is, the implementation of the Mapper interface methods is still implemented using the interface methods of SqlSession).

Four important objects of SqlSession

  1. Execute: Dispatches the execution of StatementHandler, ParmmeterHandler, and ResultHandler to execute the corresponding SQL statements;
  2. StatementHandler: Uses the Statement (PrepareStatement) in the database to execute operations, which is essentially a encapsulated prepareStatement.
  3. ParammeterHandler: Handles SQL parameters.
  4. ResultHandler: Assembles and returns the result set ResultSet.

Four Major Objects of SqlSession#

Execute#

It acts as a bridge between Java and the database for interaction and participates in the entire SQL execution process. Classification

  1. SIMPLE: Simple executor (default)
  2. REUSE: Reusable prepared statement executor
  3. BATCH: Batch update, batch-specific processor

Source code

package org.apache.ibatis.session;
public enum ExecutorType {  SIMPLE, REUSE, BATCH}

Role

Dispatches other objects to complete pre-compilation, parameter configuration, and result set return.

StatementHandler#

Classification (corresponding to different executors)

  • SimpleStatementHandler
  • PrepareStatementHandler
  • CallableStatementHandler

Role

Specifically handles database sessions. Perform pre-compilation and call ParameterHandler to configure parameters. Generally speaking, it only encapsulates the connection to the database.

Workflow

  1. Generate StatemenetHandler through the RoutingStatementHandler by calling the RoutingStatementHandler object.
  2. RoutingStatementHandler looks for the corresponding statementHandler object.
  3. statementHandler calls the database method.

ParameterHandler#

Role

Sets parameters for pre-compiled statements.

Workflow

  1. Get the parameters from the parameterObject, and then use the typeHandler (registered in Configuration) to process the parameters.

ResultSetHandler#

Role

Assembles and returns the result set.

Summary of the Running Process#

  1. Prepare pre-compilation
  2. Parameterize set parameters
  3. doUpdate/doQuery execute SQL

Summary by experts

image

Reference links

Mybatis Cache (1) - System Cache and Simple Configuration Introduction

Principle of MyBatis SqlSession

MyBatis from Entry to Give Up 6: Lazy Loading, Level One Cache, Level Two Cache

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.