2020 Mybatis source code interpretation

Why do you need the ORM framework Mybatis

  • JDBC has a heavy workload and requires at least five steps to operate the database
  • Business code and technical code coupling
  • The connection resource is manually closed, which brings hidden dangers
  • The three giants
    Connection get a connection
    PreparedStatement to precompile the sql statement
    ResultSet returns the result

ORM framework-formerly Ibatis

Three elements of Mysql mapping file:

  • SQL
  • Mapping rule
  • POJO

Mybatis independent development-quick start

  • 1. Add mybatis dependency
  • 2. Add mybatis configuration file
  • 3. Scene introduction
  • 4. Write entity classes, mapper, and mapper.xml
  • 5. Write example code

mybatis core configuration xml

  • mybatis-config.xml
  • Entity class mapper interface mapper.xml;
  • Corresponding to different interfaces through namespace, and methods corresponding to different ids;

Principle : Read the configuration file to create the SqlSessionFactory, get the Sqlsession, get the corresponding mapper configuration file and execute the corresponding SQL statement.
Core class : SqlsessionFactoryBuilder: read configuration information.
Builder mode : build SqlsessionFactory, method-level life cycle.

SqlsessionFactory : Create sqlsession, factory singleton mode exists in the entire program life cycle
Sqlsession : thread is not safe, guarantee thread exclusive (method level)
SQLMapper : consists of a Java interface and XML file, contains the SQL statement to be executed and the result set Mapping, method-level life cycle;

resultType or resultMap mapping relationship

  • resultType corresponds to a POJO
  • resultMap attributes:
    • id unique identification
    • type corresponding POJO
    • autoMapping is true by default, and automatically map fields and attributes
    • Sub-elements:
      id: marking the id can improve the overall retrieval performance, one-to-many for the result collection and
      result: one
      -to- one correspondence with the JavaBean attribute type association: one-to-one query
      collection: one-to-many query
  • ResultMap can simplify configuration through inheritance; it is a good habit to prefix associated tables;
  • The resultMap of other xml files can be referenced through the complete namespace;
  • The resultMap is mandatory in the Ali development manual:
    Reason : decoupling, if the database is modified one day, only the configuration file needs to be changed, without the need to change the code to recompile, etc.

How to pass multiple parameters?

  • 1. Entity class-commonly used
  • 2. Map transfer is poor in readability and maintainability, so it is forbidden to use it
  • 3. @Param annotation transfer-simple and clear, it is recommended to use less than 5 parameters

How to get the primary key?

  • useGeneratedKeys:true
  • keyProperty : id

SQL elements and SQL parameters

Pre-compilation #{} is pre-compiled, and treats the passed parameter as a string (plus single quotes), which can prevent SQL injection to a large extent; the data passed in by the
value ${} is directly displayed in the SQL statement, Cannot prevent SQL injection;

Dynamic SQL

  • if single conditional branch judgment
  • choose/when/otherwise multi-conditional branch judgment
  • trim handles insert/where search/set update handles SQL assembling problem
  • The foreach in statement is commonly used to process batch operations

Frequent interview questions: how to perform batch operations through Mybatis

  • Assemble sql statement through foreach
  • Will use BATCH type excutor (executor)

Mybatis Generator MBG code generator:

  • Generate entity classes, Mapper interfaces, and mapper.xml files from database tables
  • generatorConfiguration: root node
  • context: context
  • Three ways of code generator: Maven Plugin, Java program startup, command line use

Associated query

  • The associated field needs to have an index. If there are more than three tables with join associations
    , two queries can be performed
  • Nested results and nested queries

How to use lazy loading in mybatis

mybatis cache

The first level cache is turned on by default, and the first level cache is turned off. On the select tab, flushCache="true"
. When the life cycle of the first level cache is a session (Sqlsession)
update/insert/delete, the cache will be cleared.

The second level cache is turned off by default

Existing in SqlsessionFactory,
dirty reads are prone to cross-sqlsession second-level caches. It is recommended to avoid using second-level caches and use controllable caches instead of (redis) in the business layer.

Mybatis source code in-depth

Mybatis overall architecture

  • Basic support layer: data source, transaction management, cache, Binding module, reflection, type conversion, log module, resource loading, parser
  • Core processing layer: configuration analysis, parameter mapping, SQL analysis, SQL execution, result set mapping, plug-ins
  • Interface layer: SqlSession

Appearance mode (facade mode) : Provides a unified interface to access a group of interfaces in the subsystem. The appearance mode defines a high-level interface to make the subsystem easier to use;
encapsulate specific details inside, and only expose the necessary interfaces to the outside;
see the source code must :

  • Dynamic agency basic technology basic
    design principles ideological basis
  • Single responsibility principle
  • Dependency inversion principle: interface-oriented programming, when the implementation changes, only new implementation classes are provided, without the need to modify the code of high-level modules;
  • (Most important) Open-closed principle: the program is open for external expansion and closed for modification. That is, when the requirements change, we can add new modules to meet the new requirements, instead of modifying the original code to meet the new requirements.
  • Dimit's rule: An object should keep a minimum of understanding of other objects, and minimize the coupling between classes;
  • Richter substitution principle:
  • Interface isolation principle

Basic support layer source code analysis-log module requirements

Mybatis does not provide log implementation classes and needs to be connected to third-party log components. Third-party log components have different log levels and are different. Mybatis provides four levels of trace, debug, warn, and error;
automatic scan log implementation , And the third-party plug-in loading priority is: slf4j–commonsLoging–Log4j2–Log4j–jdkLog

The use of logs is elegantly embedded in the main function.
BaseJdbcLogger: The abstract base class for all log enhancements;
ConnectionLogger: Responsible for printing connection information and SQL statements, and creating PreparedStatementLogger;
PreparedStatementLogger: Responsible for printing parameter information and creating ResultSetLogger;
ResultSetLogger: Responsible for printing data Result information;

ConnectionLogger, PreparedStatementLogger, and ResultSetLogger all implement dynamic proxy;
Adapter mode : As a bridge between two incompatible interfaces, it converts an interface of one class into another interface that the customer wants. The adapter mode allows the originally incompatible interfaces to work together .
Target: the target role, the interface expected;
Adaptee: the role of the adaptor, the interface being adapted;
Adapter: the role of the adapter, which converts the source interface into the target interface;
applicable scenarios: when the calling parties are not easy to modify, for reuse Existing components can use the adapter mode; it is often used when accessing third-party components in the system;

Proxy mode : Provide a proxy object to the target object, and the proxy object controls the reference of the target object;
Purpose: Indirect access to the target object by introducing the proxy object to prevent unnecessary system complexity caused by direct access to the target object; through proxy The object enhances the original business;

Where does Mybatis need to print logs:

  • When creating prepareStatement, print and execute SQL statement;
  • When accessing the database, print the type and value of the parameter;
  • When querying the result, print the number of result data;

Log module JDBC package class diagram

Insert picture description here

  • ConnectionLogger : Responsible for printing connection information and SQL statements, and creating PrepareStatementLogger;
  • PrepareStatementLogger : Responsible for printing parameter information and creating ResultSetLogger;
  • ResultSetLogger : Responsible for printing data result information;

Data source module analysis

Difficulties in creating a data source by analyzing the source code of the basic support layer

  • Common data source components all implement the javax.sql.DataSource interface;
  • Mybatis not only integrates third-party data source components, but also provides the implementation of data sources itself;
  • In general, the initialization parameters of the data source are many and more complicated;

Factory pattern (Factory Pattern): belongs to the creation mode, it provides a best way to create objects. Define an interface to create an object, let its subclasses feel which factory class to instantiate, the factory pattern delays the creation process to the subclass;
Product interface (Product) : the product interface is used to define the function of the product class, the specific factory class All products produced must implement this interface. The caller interacts directly with the product interface, which is the interface that the caller cares most about;
ConcreteProduct : the implementation class that implements the product interface, and the specific business logic is defined in the specific product class;
**Factory interface (Factory): **The factory interface is the core interface of the factory pattern. The caller will directly interact with the factory interface to obtain a specific product implementation class;
ConcreteFactory: the implementation class of the factory interface, used to instantiate product objects, different Specific factory classes instantiate different product implementation classes according to requirements;
simple factory mode

Why use the factory model?

Insert picture description here

The creation of the object is decoupled from the use process of the object, which is convenient for expansion. You do not need to modify the original code, and you can directly add factory classes for new functions and new requirements.

Data connection pool core class

  • PooledDataSource: a simple, synchronized, thread-safe database connection pool;
  • PooledConnection: Use dynamic proxy to encapsulate the real database connection object;
  • PoolState: A component used to manage the state of the PooledConnection object, through two lists to manage the connection resources in the idle state and the connection resources in the active state respectively;
    PooledDataSource obtains and returns the connection process:
    Insert picture description here
    Insert picture description here

Basic support layer source code analysis-cache module requirements

Decorator mode : It is a technology used to replace inheritance. It can extend the new functions of objects without extending subclasses through inheritance. It uses the association relationship of objects to replace inheritance, which is more flexible and avoids the rapid expansion of the type system;
Insert picture description here

Component : The component interface defines the behavior of all component classes and decorators; the
component realization class (ConcreteComponent) : realizes the Component interface. The component realization class is the original object decorated by the decorator. New functions or additional functions are passed The decorator is added to the object of this class; the
decorator abstract class (Decorator) : an abstract class that implements the Component interface, in which a Component object is encapsulated, which is the object to be decorated; the
concrete decorator class (ConcreteDecorator) : the The implementation class should be added to the decorated object;
advantages

  • Compared with inheritance, the decorator model is more flexible and more extensible;
  • Flexibility: The decorator mode divides the functions into independent decorators, which can be dynamically added according to needs during the runtime, or even freely combined with the new functions added;
  • Extensibility: When there is a new function to be added, you only need to add a new decorator implementation class, and then add this new decorator through combination, without modifying the existing code, conforming to the opening and closing principle;
    examples of using decorator mode
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("c://a.txt")));

Mybatis cache component
Insert picture description here

  • Cache : The Cache interface is the core interface of the cache module, which defines the basic operation of the cache;
  • PerpetualCache : Play the role of ConcreteComponent in the cache module, and use HashMap to implement cache related operations;
  • BlockingCache : Blocking version of the cache decorator to ensure that only one thread goes to the database to find the data corresponding to the specified key;

Interpretation of cache decorators

  • FifoCache: First-in, first-out cache elimination strategy
  • LoggingCache: Cache for logging capabilities
  • ScheduledCache: Cache that is emptied regularly
  • BlokingCache: blocking cache
  • SeralizedCache: Cache with serialization capability
  • SynchronizedCache: Cache for synchronization control.
    Some functions;
    CacheKey

Dynamic SQL is involved in MyBatis. The key of the cache item cannot be represented by a String alone, so the key value of the cache is encapsulated by CacheKey. CacheKey can encapsulate multiple factors that affect the cache item; the key to judging whether two CacheKeys are the same is Compare whether the hash values ​​of the two objects are consistent;

Objects that make up the CacheKey

  • mappedStatment的id
  • Specify the range of the query result set (pagination information)
  • SQL statement used in the query
  • The actual parameter value passed by the user to the SQL statement

Reflection module analysis

Orm framework query data process
Load data from the database -> find the mapping matching rules -> instantiate the target object -> assign object properties

The core class of reflection

  • ObjectFactory : Every time Mybatis creates a new instance of the result, it will use the ObjectFactory to construct the POJO;
  • ReflectorFactory : Create a factory class for Reflector. Reflector is the basis of the Mybatis reflection module. Each Reflector object corresponds to a class in which the class meta information required for reflection operations is cached;
  • ObjectWrapper : The packaging of objects abstracts the property information of objects. It defines a series of methods for querying object property information and methods for updating properties;
  • ObjectWrapperFactory : The factory class of ObjectWrapper, used to create ObjectWrapper;
  • MetaObject : encapsulates the meta information of the object, and encapsulates the five core reflection classes in MyBatis. It is also a reflection tool class for external use, which can be used to read or modify the attribute information of the object;
    Insert picture description here

Three stages of Mybatis core process

Insert picture description here

  • Initialization stage: Read the configuration information in the XML configuration file and annotations, create configuration objects, and complete the initialization of each module;
  • Encapsulate the programming model of iBatis, use the mapper interface to develop and initialize the work;
  • Complete SQL analysis, parameter mapping, SQL execution, and result analysis process through SqlSession;

Configuration loading phase

Mybatis initializes the builder mode

  • Builder Pattern: Use multiple simple objects to build a complex object step by step. This type of design pattern is a creational pattern, which provides the best way to create objects.
    Insert picture description here
  • Product (product) : the complex object to be created;
  • Builder (builder) : Gives an abstract interface to standardize the construction of each component of the product object. This interface specifies which parts of the complex object are to be created, and does not involve the creation of specific object parts;
  • ConcreteBuilder (concrete builder) : implements the Builder interface, and concretizes the creation of various parts of complex objects for different business logic. After the completion of the construction process, provide examples of products;
  • Director (director) : call a specific builder to create each part of a complex object. The director does not involve specific product information, but is only responsible for ensuring that each part of the object is created completely or in a certain order;

Builder mode usage scenarios

  • The object that needs to be generated has a complex internal structure. When you instantiate the object, you must shield the internal details of the object to decouple the upper-level code from the instantiation process of the object. You can use the builder mode; in short: if you encounter multiple Consider using the builder when constructing the parameters of the constructor";
  • The instantiation of an object depends on the production and assembly sequence of each component. The focus is on the step-by-step assembly of the target object. You can use the builder mode;
Design Patterns Image metaphor Object complexity Client participation level
Factory mode Mass production What you care about is the whole of a product, and you don't need to care about how each part of the product is created. The client's participation in the product creation process is low, and the attribute values ​​are relatively fixed when the object is instantiated
Builder mode Production customized version The object to be built is more complex, it is a composite product, which is composed of various components, and the product objects are different for different components, and the generated product has a fine granularity; The client participates in the creation of the product, feels the type and content of the product, and has a high degree of participation; suitable for scenarios where attributes change frequently when instantiating objects;

Application of builder mode in MyBatis

Insert picture description here

  • SqlSessionFactoryBuilder creates SqlSessionFactory
  • XMLConfigBuilder , XMLMapperBuilder , XMLStatementBuilder create configuration objects
  • CacheBuilder creates a secondary cache
  • ResultMapping Builder creates ResultMapping objects

MyBatis builder class diagram
Insert picture description here

  • BaseBuilder : The parent class of all parsers, including configuration file examples, and some common methods for parsing files;
  • XMLConfigBuilder : Mainly responsible for parsing mybatis-config.xml;
  • XMLMapperBuilder : Mainly responsible for parsing mapping configuration files;
  • XMLStatementBuilder : Mainly responsible for parsing the SQL node in the mapping configuration file;

Mybatis initialization

Insert picture description here

Ali interview question: Why can the database be developed using the mapper interface?
Insert picture description here
The key class of the mapper

  • Configuration : The core of Mybatis startup initialization is to load all the xml configuration file information into the Configuration object. Configuration is a singleton, and the life cycle is application-level;
  • MapperRegistry : The registration center of the dynamic proxy factory class of the mapper interface. In Mybatis, the InvocationHandler interface is implemented through mapperProxy, and MapperProxyFactory is used to generate dynamic proxy instance objects;
  • ResultMap: used to parse the resultMap node in the mapper.xml file, and use ResultMapping to encapsulate child elements such as id and result;
  • MappedStatement : used to store the selsct, insert, update and delete nodes in the mapper.xml file, and also contains
    many important attributes of these nodes;
  • SqlSource : When the user creates BoundSql, the SQL statement in mapper.xml will be parsed into BoundSql objects. The parsed BoundSql statement contains only the? Placeholder at the end, which can be directly submitted to the database for execution;

ResultMap diagram
Insert picture description here

Configuration file interpretation + dynamic proxy enhancement

Binding module analysis

Executor component analysis

Template mode

  • Executor is one of the core interfaces of Mybatis, which defines the most basic method of database operation. The functions of SqlSession are realized based on it;
    programming experience and skills, and the idea of ​​source code.
    First understand the data structure, and then discuss the algorithm in detail

Guess you like

Origin blog.csdn.net/weixin_42292697/article/details/109788159