MyBatis core component——Configuration

Overview

The core components of Mybatis are as follows:

  • Configuration: Used to describe the main configuration information of MyBatis. When other components need to obtain configuration information, they can obtain it directly through the Configuration object. In addition, MyBatis registers Mapper configuration information, type aliases, TypeHandler, etc. into the Configuration component when the application starts. When other components need this information, they can also obtain it from the Configuration object.
  • MappedStatement: used to describe the SQL configuration information in Mapper. It is an encapsulation of the configuration information of tags or annotations <select|update|delete|insert>in the Mapper XML configuration file.@Select/@Update
  • SqlSession: It is a user-oriented API provided by MyBatis, which represents the session object when interacting with the database, and is used to complete the addition, deletion, modification and query functions of the database. SqlSession is the appearance of the Executor component. It aims to provide an easy-to-understand and use database operation interface to the outside world.
  • Executor: MyBatis's SQL executor. All MyBatis's addition, deletion, modification and query operations on the database are completed by the Executor component.
  • StatementHandler: encapsulates the operations on the JDBC Statement object, such as setting parameters for the Statement object, calling the methods provided by the Statement interface to interact with the database, etc.
  • ParameterHandler: When the Statement type used by the MyBatis framework is CallableStatcment and PreparedStatement, ParamelerHandler is used to set values ​​for the Statement object parameter placeholders.
  • ResultSetHandler: ResultSetHandler encapsulates JDBC ResultSet object operations. When executing a SQL type SELECT statement, ResultSetHandler is used to convert the query results into Java objects.
  • TypeHandler: TypeHandler is a type processor in MyBatis, used to handle the mapping between Java types and JDBC types. Its function is mainly reflected in being able to call the set method corresponding to the PreparedStatement or CallableStatement object according to the Java type to set the value for the Statement object, and Can call the get corresponding to the ResultSet object according to the Java type to obtain the SQL execution result

When using MyBatis, we use the SqlSession component, which is a user-level API. In fact, SqlSession is the appearance of the Executor component, with the purpose of providing users with a more friendly database operation interface. This is a typical application of the appearance pattern in the design pattern. What actually performs SQL operations is the Executor component. Executor can be understood as a SQL executor, which uses the StatementHandler component to operate on the JDBC Statement object. When the Statement type is CallableStatement and PreparedStatement, the parameter placeholder will be assigned a value through the ParameterHandler component. The ParameterHandler component will find the corresponding TypeHandler object according to the Java type. The TypeHandler will set the value for the parameter placeholder in the Statement object through the set method provided by the Statement object. After the StatementHandler component uses the Statement object in JDBC to complete the interaction with the database, when the SQL statement type is SELECT, MyBatis obtains the ResultSet object from the Statement object through the ResultSetHandler component, and then converts the ResultSet object into a Java object.


Configuration

There are two types of configuration information for the MyBatis framework. One is the main configuration file that configures the properties of the MyBatis framework; the other is the Mapper configuration file that configures the execution of SQL statements. The role of Configuration is to describe the information of the MyBatis main configuration file. The Configuration class defines a series of properties to control MyBatis runtime behavior. The codes for these properties are as follows:

public class Configuration {
    
    
	protected boolean safeRowBoundsEnabled;
	protected boolean safeResultHandlerEnabled = true;
	protected boolean mapUnderscoreToCamelCase;
	protected boolean aggressivelazyLoading;
	protected boolean multipleResultSetsEnabled = true;
	protected boolean useGeneratedKeys;
	protected boolean useColumnLabel = true;
	.......
}

The values ​​of these properties can be specified via tags in the main MyBatis configuration file <setting>, for example:

<settings>
	<setting name="cacheEnabled" value="true"/>
	<setting name="lazyLoadingEnabled" value="true"/>
</settings>

The functions and configuration descriptions of all attributes are as follows:

  • cacheEnabled: Whether to enable the Mapper cache, that is, the second level cache, the default is true
  • lazyLoadingEnabled: global switch for lazy loading. When enabled, all associated objects are loaded lazily. In a specific association, the switch status of the item can be overridden by setting the fetchType attribute. The default is false.
  • aggressiveLazyLoading: When turned on, any method call will load all properties of the object. Otherwise, each attribute will be loaded on demand. The default is false. Before 3.4.1, the default was true.
  • multipleResultSetsEnabled: Whether a single statement is allowed to return multiple result sets, default true
  • useColumnLabel: Use column labels instead of column names. Different drivers will perform differently in this regard. The default is true.
  • useGeneratedKeys: Allows JDBC to support automatic generation of primary keys and requires driver compatibility. If set to true, this setting forces the use of automatically generated primary keys. Although some drivers are incompatible, it can still work normally. The default is false.
  • autoMappingBehavior: Specify how MyBatis should automatically map columns to Java entity properties. NONE means to cancel automatic mapping, and PARTIAL will only automatically map result sets that do not define nested result set mapping. FULL will automatically map any complex result set (whether nested or not), the default is PARTIAL
  • autoMappingUnknownColumnBehavior: Specifies the behavior of discovering unknown columns (or unknown attributes) of automatic mapping targets. NONE: No response, WARNING: Output reminder log, FAILING: Mapping failed, exception thrown, default NONE
  • defaultExecutorType: configure the default Executor type, SIMPLE is an ordinary Executor; REUSE will reuse Statement objects; BATCH will execute all update statements in batches, the default SIMPLE
  • defaultStatementTimeout: Set the timeout, which determines the number of seconds the driver waits for the database response. It can be said to be any positive integer. The default is null and is not set.
  • defaultFetchSize: Default FetchSize, used to set the fetchSize property of the Statement object, used to limit the maximum number of rows to obtain data from the database, the default is null, not set
  • SafeRowBoundsEnabled: Allows the use of paging (RowBounds) in nested statements. If it is allowed, set it to false. The default is false.
  • safeResultHandlerEnabled: Allows the use of paging (ResultHandler) in nested statements. If it is allowed, set it to false. The default is false.
  • mapUnderscoreToCamelCase: Whether to turn on the automatic camel case naming rule mapping, that is, the mapping from the classic database column name A_COLUMN to the classic Java attribute name aColumn
  • localCacheScope: MyBatis uses the local cache mechanism to prevent circular references and speed up repeated queries. The default value is SESSION, in which case all queries executed within a session are cached. If the setting value is STATEMENT, the local session is only used for statement execution, and different calls to the same SqlSession will not share data.
  • jdbcTypeForNuIl: When no JDBC type is specified for the parameter, the value of the specified JDBC type is null. Some drivers need to specify the JDBC type. In most cases, just use the general type, such as NULL, VARCHAR or OTHER. The default is OTHER.
  • lazyLoadTriggerMethods: specifies which object method will trigger a lazy load, the parameter is a comma-separated method list
  • defaultScriptingLanguage: Specifies the default language generated by dynamic SQL. The parameter value is a type alias or fully qualified class name. Default value: org.apache.ibatis.XMLLanguageDriver
  • defaultEnumTypeHandler: Specifies the default TypeHandler used by Java enumeration types. Default value: org.apache.ibatis.type.EnumTypeHandler
  • callSettersOnNulls: Specifies whether to call the Setter method of the mapping object when the value in the result set is null. This is useful when there is a Map.keySet() dependency or null value initialization. Note that basic types (int, boolean, etc.) cannot be set to null, and the default is false.
  • returnInstanceForEmptyRow: When all columns of the returned row are empty, MyBatis returns null by default. When this setting is turned on, MyBatis will return an empty instance. Please note that this also applies to nested result sets (collection, association), default false
  • logPrefix: Specify the prefix that MyBatis adds to the log name. It is not set by default.
  • loglmpl: Specify the specific implementation of the log used by MyBatis. If not specified, it will be automatically searched. SLF4J, LOG4J, etc. can be set. It is not set by default.
  • proxyFactory: Specify the proxy tool used by MyBatis to create objects with lazy loading capabilities. Optional values ​​include JAVASSIST and CGLIB. The default is JAVASSIST.
  • vfsImpl: Specify the implementation of VFS. The parameter is the fully qualified name of the VFS implementation class, separated by commas. It is not set by default.

In addition to providing the above properties to control the behavior of MyBatis, Configuration also serves as a container to store TypeHandler (type processor), TypeAlias ​​(type alias), Mapper interface and MapperSQL configuration information. This information is registered in the Configuration component when the MyBatis framework starts. The Configuration class saves TypeHandler, TypeAlias ​​and other information through the following properties:

protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
protected final InterceptorChain interceptorChain = new InterceptorChain();
protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
protected final TypeAliasRegistry typeAliasRegistry= new TypeAliasRegistry();
protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");
protected final Set<String> loadedResources = new HashSet<String>();
protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");
protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>();
protected final Collection<CacheRefResolver> incompletecacheRefs = new LinkedList<CacheRefResolver>()
protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>();
protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>();
protected final Map<String, String> cacheRefMap = new HashMap<String, String>();

The meaning of these properties is as follows:

  • mapperRegistry: used to register Mapper interface information and establish the relationship between the Class object of the Mapper interface and the MapperProxyFactory object. The MapperProxyFactory object is used to create the Mapper dynamic proxy object.
  • interceptorChain: used to register MyBatis plug-in information. The MyBatis plug-in is actually an interceptor.
  • typeHandlerRegistry: used to register all TypeHandlers and establish the correspondence between Jdbc types, JDBC types and TypeHandlers
  • typeAliasRegistry: used to register all type aliases
  • languageRegistry: used to register LanguageDriver, LanguageDriver is used to parse SQL configuration and convert configuration information into SqlSource objects
  • mappedStatements: MappedStatement object description <insert|selectlupdateldelete>and other tags or @Select|@Delete|@Update|@InsertSQL information configured through other annotations. MyBatis registers all MappedStatement objects into this property, where Key is the Id of the Mapper and Value is the MappedStatement object.
  • caches: used to register all cache information configured in Mapper, where Key is the id of Cache, which is the namespace of Mapper, and Value is the Cache object.
  • resultMaps: used to register the ResultMap information configured through tags in the Mapper configuration file. ResultMap is used to establish the mapping relationship between Java entity attributes and database fields. The Key is the id of the ResultMap, which is the id of the Mapper namespace and tag. It consists of attributes, and Value is the ResultMap object obtained after parsing the tag.
  • parameterMaps: used to register parameter mapping information registered through tags in Mapper. Key is the id of ParameterMap, which is composed of the Mapper namespace and the id attribute of the label. Value is the ParameterMap object obtained after parsing the label.
  • keyGenerators: used to register KeyGenerator. KeyGenerator is the primary key generator of MyBatis. MyBatis provides three KeyGenerators, namely Jdbc3KeyGenerator (database auto-increment primary key), NoKeyGenerator (no auto-increment primary key), SelectKeyGenerator (query auto-increment primary key through select statement, for example oracle sequence)
  • loadedResources: used to register all Mapper XML configuration file paths
  • sqlFragments: used to register SQL fragments configured through tags in Mapper. Key is the id of the SQL fragment, and Value is the XNode object encapsulated by MyBatis that represents the XML node.
  • incompleteStatements: XMLStatementBuilder object used to register parsing exceptions
  • incompleteCacheRefs: used to register CacheRefResolver objects that experience exceptions in parsing
  • incompleteResultMaps: used to register ResultMapResolver objects that experience exceptions in parsing
  • incompleteMethods: MethodResolver object used to register exceptions in parsing

When the MyBatis framework starts, it will parse all configuration information, and then register the parsed content into these properties of the Configuration object. In addition, the Configuration component also serves as the factory class for the Executor, StatementHandler, ResultSetHandler, and ParameterHandler components to create instances of these components.

Guess you like

Origin blog.csdn.net/CSDN_handsome/article/details/132044331