Beauty of Mybatis source code: 2.11. Initialize global configuration through settings configuration

Posted by aQ on Sat, 27 Jun 2020 07:43:54 +0200

Initialize global configuration through settings configuration

When it comes to initializing the global Configuration of Mybatis through settings, it is difficult for us to bypass the Configuration object of Mybatis.

Configuration object is undoubtedly one of the core objects of Mybatis. It defines many properties and methods. In the process of parsing, we may encounter some properties or methods that we don't know their specific functions. Don't worry. In the subsequent parsing process, we will slowly fill in the understanding of configuration object.

First, paste out the properties of the Configuration object. Let's have a general look. There is an impression that in the later analysis process, we will gradually talk about the role of each property.

This chapter may be boring, but it can also make us more proficient in the use of mybatis.

<details> <summary> Configuration.java (code overview, can be skipped) < / summary >

/**
* Mybatis Configuration class
* All configurations of Mybatis and metadata containers of Mapper files are provided
*
* @author Clinton Begin
*/
public class Configuration {

    /**
     * Environmental information, including data such as transactions and data sources
     */
    protected Environment environment;
    /**
     * Whether {@ link RowBounds} is allowed to perform paging operations in nested statements
     */
    protected boolean safeRowBoundsEnabled;
    /**
     * Whether {@ link ResultHandler} is allowed to perform paging operations in nested statements
     */
    protected boolean safeResultHandlerEnabled = true;
    /**
     * Convert underscores to humps
     */
    protected boolean mapUnderscoreToCamelCase;
    /**
     * Whether to allow all properties of the object to be loaded directly when the method is called
     */
    protected boolean aggressiveLazyLoading;
    /**
     * Allow single statement to return multiple result sets
     */
    protected boolean multipleResultSetsEnabled = true;
    /**
     * Allow JDBC to generate primary key automatically
     */
    protected boolean useGeneratedKeys;
    /**
     * Use column labels instead of column names
     */
    protected boolean useColumnLabel = true;
    /**
     * Enable caching or not
     */
    protected boolean cacheEnabled = true;
    /**
     * Whether to still set the value when the content is null
     */
    protected boolean callSettersOnNulls;
    /**
     * Whether to use the actual parameter name can reduce {@ link to some extent org.apache.ibatis . annotations.Param }Code of
     */
    protected boolean useActualParamName = true;
    /**
     * Allow to return an empty instance when the content cannot be obtained
     * In general, if the returned content of the query result is null, MyBatis returns null by default. If this function is enabled, it will return an empty instance
     */
    protected boolean returnInstanceForEmptyRow;
    /**
     * Mybatis Log prefix
     */
    protected String logPrefix;
    /**
     * Log implementation class, if not implemented, automatically find
     */
    protected Class<!--? extends Log--> logImpl;
    /**
     * Virtual file system provides a simple API to access system file resources
     */
    protected Class<!--? extends VFS--> vfsImpl;
    /**
     * Cache life cycle
     * MyBatis Local Cache is used to prevent circular references and accelerate nested queries.
     * The default is SESSION, which caches all queries executed in a SESSION
     * If the value is set to STATEMENT, the local session is only used for STATEMENT execution, and different calls to the same SqlSession will not share data.
     */
    protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
    /**
     * Type of field in the database
     * When no specific JDBC type is provided for the parameter, specify the JDBC type for the null value.
     * Some drivers need to specify the JDBC type of the column. In most cases, you can use the general type directly, such as NULL, VARCHAR or OTHER.
     */
    protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
    /**
     * Trigger method of lazy loading
     */
    protected Set<string> lazyLoadTriggerMethods = new HashSet&lt;&gt;(Arrays.asList("equals", "clone", "hashCode", "toString"));
    /**
     * {@link java.sql.Statement}It determines the number of seconds the driver waits for the database to respond. It does not timeout by default
     */
    protected Integer defaultStatementTimeout;
    /**
     * Get the default size of data
     * Sets the default fetch quantity for the driven result set.
     */
    protected Integer defaultFetchSize;
    /**
     * The type of behavior of the actuator to use when executing expectations
     * Among them:
     * {@link ExecutorType#SIMPLE} A new preprocessing statement ({@ link) is created for each statement execution java.sql.PreparedStatement }
     * {@link ExecutorType#REUSE} Reuse preprocessing statements
     * {@link ExecutorType#BATCH} Reuse preprocessing statements and perform batch operations
     */
    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
    /**
     * Automatic mapping behavior definition
     * {@link AutoMappingBehavior#NONE} Disable automatic mapping
     * {@link AutoMappingBehavior#PARTIAL} Local automatic mapping, only mapping the result set without defining nested result set mapping
     * {@link AutoMappingBehavior#FULL} Full automatic mapping, automatically mapping any complex result set (nested or not)
     */
    protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
    /**
     * Processing behavior when automatic mapping encounters unrecognized fields
     * {@link AutoMappingUnknownColumnBehavior#NONE} Do nothing
     * {@link AutoMappingUnknownColumnBehavior#WARNING} Output warning log
     * {@link AutoMappingUnknownColumnBehavior#FAILING} Terminate the automap and throw an exception
     */
    protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
    /**
     * Property configuration properties under configuration - & gt; settings
     */
    protected Properties variables = new Properties();
    /**
     * Configure reflection factories to simplify operational properties and constructors
     */
    protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
    /**
     * Configure object creation factory
     */
    protected ObjectFactory objectFactory = new DefaultObjectFactory();
    /**
     * Configure the object wrapper factory, which is mainly used to create non-native objects
     */
    protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
    /**
     * Whether lazy loading is enabled. When on, all associated objects delay loading. The switch state of the item can be overridden by setting the fetchType property in a specific association.
     */
    protected boolean lazyLoadingEnabled = false;
    /**
     * Proxy factory, which specifies the proxy tool used by Mybatis to create lazy load objects
     */
    protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
    /**
     * The unique flag of database type. Mybatis can execute different statements according to different database vendors. The implementation of this function depends on this flag.
     */
    protected String databaseId;
    /**
     * Configuration factory
     * Configuration factory class.
     * Used to create Configuration for loading deserialized unread properties.
     *
     * @see <a href="https://code.google.com/p/mybatis/issues/detail?id=300">Issue 300 (google code)</a>
     */
    protected Class<!--?--> configurationFactory;
    /**
     * Dao Operation object registry
     */
    protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
    /**
     * Blocker responsibility chain (Mybatis plug-in)
     */
    protected final InterceptorChain interceptorChain = new InterceptorChain();
    /**
     * Type processor registry
     */
    protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
    /**
     * Type alias registry is mainly used for entering and exiting parameters of executing SQL statements and shorthand of some classes
     */
    protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
    /**
     * Language support driver registry
     */
    protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
    /**
     * Statement mapping table
     */
    protected final Map<string, mappedstatement> mappedStatements = new StrictMap<mappedstatement>("Mapped Statements collection")
            .conflictMessageProducer((savedValue, targetValue) -&gt;
                    ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
    /**
     * Cache mapping table
     */
    protected final Map<string, cache> caches = new StrictMap&lt;&gt;("Caches collection");
    /**
     * ResultMap Mapping table
     */
    protected final Map<string, resultmap> resultMaps = new StrictMap&lt;&gt;("Result Maps collection");
    /**
     * Parameter mapping table
     */
    protected final Map<string, parametermap> parameterMaps = new StrictMap&lt;&gt;("Parameter Maps collection");
    /**
     * Primary key generator mapping table
     */
    protected final Map<string, keygenerator> keyGenerators = new StrictMap&lt;&gt;("Key Generators collection");

    /**
     * A collection of loaded resources that can be used to prevent duplicate loading of files
     */
    protected final Set<string> loadedResources = new HashSet&lt;&gt;();
    /**
     * Code block map set
     */
    protected final Map<string, xnode> sqlFragments = new StrictMap&lt;&gt;("XML fragments parsed from previous mappers");

    /**
     * Declaration statement not processed
     */
    protected final Collection<xmlstatementbuilder> incompleteStatements = new LinkedList&lt;&gt;();
    /**
     * Outstanding cache references
     */
    protected final Collection<cacherefresolver> incompleteCacheRefs = new LinkedList&lt;&gt;();
    /**
     * Unfinished return result mapping
     */
    protected final Collection<resultmapresolver> incompleteResultMaps = new LinkedList&lt;&gt;();
    /**
     * Collection of unfinished methods
     */
    protected final Collection<methodresolver> incompleteMethods = new LinkedList&lt;&gt;();

    /*
     * Cache reference mapping
     * Cache references =) cache
     */
    protected final Map<string, string> cacheRefMap = new HashMap&lt;&gt;();

    public Configuration(Environment environment) {
        this();
        this.environment = environment;
    }

    public Configuration() {
        // Register alias

        // Register JDBC alias
        typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
        // Register transaction management alias
        typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
        // Register JNDI alias
        typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
        // Register pooled data source alias
        typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
        // Register as a pooled data source
        typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
        // Register permanent cache
        typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
        // Register first in first out cache
        typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
        // Register recent minimum cache usage
        typeAliasRegistry.registerAlias("LRU", LruCache.class);
        // Register soft cache
        typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
        // Register weak cache
        typeAliasRegistry.registerAlias("WEAK", WeakCache.class);
        // Register the provider that processes the database ID
        typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
        // Register XML based language driver
        typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
        //Register static language drivers (usually not required)
        typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
        // Register Sl4j log
        typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
        //Register Commons log
        typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
        //Register log4j log
        typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
        //Register log4j2 log
        typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
        //Register jdk log log
        typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
        //Register standard output log
        typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
        //No log for registration
        typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
        // Register CGLIB
        typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
        // Register JAVASSIST
        typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
        // XML language driven by default
        languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
        // Support for native language drivers
        languageRegistry.register(RawLanguageDriver.class);
    }

</string,></methodresolver></resultmapresolver></cacherefresolver></xmlstatementbuilder></string,></string></string,></string,></string,></string,></mappedstatement></string,></string></details>

In the settingsElement method, it is a tedious and tedious property assignment operation.

<details> < summary > settingselement (settings)

    /**
     * Override system default configuration with user-defined configuration
     *
     * @param props User defined configuration
     * @see http://www.mybatis.org/mybatis-3/zh/configuration.html#settings
     */
    private void settingsElement(Properties props) {
        // Defines how Mybatis automatically converts JDBC columns to fields or properties, which corresponds to the AutoMappingBehavior enumeration class, where
        // NONE: disable automatic mapping
        // PARTIAL: local automatic mapping, only mapping the result set without nested result set mapping defined
        // FULL: FULL automatic mapping, automatically mapping any complex result set (nested or not)
        configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));

        // Defines the behavior when a column or field that cannot be processed (recognized) using the auto mapping function is found. It corresponds to the AutoMappingUnknownColumnBehavior enumeration class, where
        // NONE: no operation
        // WARNING: output WARNING log
        // FAILING: mapping failed with SqlSessionException exception thrown
        configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));

        // Globally turn on or off any caching that all mappers in the configuration file have configured.
        configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));

        // Specifies the proxy factory used by Mybatis to create objects with delay loading capability. JavassistProxyFactory is used by default
        configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));

        // Global switch to delay loading. When on, all associated objects delay loading. The switch state of the item can be overridden by setting the fetchType property in a specific association.
        configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));

        // When on, calls to any method load all properties of the object. Otherwise, each property will be loaded on demand (refer to lazyloadtrigger methods)
        configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));

        // Whether a single statement is allowed to return multiple result sets (compatible driver is required).
        configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));

        // Whether to use column labels instead of column names.
        configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));

        // Whether to allow JDBC to generate primary key automatically requires driver compatibility.
        // If it is set to true, it forces the use of auto generate primary keys, which work well even though some drivers are not compatible (such as Derby).
        configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));

        // Configure the default actuator. Corresponding ExecutorType enumeration class
        // SIMPLE is a common actuator;
        // The REUSE executor will REUSE the prepared statements;
        // The BATCH executor will reuse statements and perform BATCH updates.
        configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));

        // Sets the timeout, which determines the number of seconds the driver waits for a response from the database.
        configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));

        // Set a prompt value for the fetchSize of the driven result set. This parameter can only be overridden in query settings.
        configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));

        // Whether to turn on the mapping of camel case, that is, from the classic database column name a_ Similar mapping from column to classic Java property name aColumn
        configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));

        // Allows paging (RowBounds) in nested statements. If allowed, set to false. OK, allowed is false.
        configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));

        // MyBatis uses the Local Cache mechanism to prevent circular references and speed up repeated nested queries.
        // The default is SESSION, which caches all queries executed in a SESSION.
        // If the value is set to STATEMENT, the local session is only used for STATEMENT execution, and different calls to the same SqlSession will not share data.
        configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));

        // When no JDBC type is specified for the parameter, when the parameter is null, the default JDBC type is NULL,VARCHAR,OTHER
        configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));

        // The trigger method of lazy loading, which specifies which method of which object triggers a lazy loading.
        configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));

        // Allows the use of a return result handler in nested statements. Set to false if allowed.
        configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));

        // Specifies the default language for dynamic SQL generation. Currently, the default is XMLLanguageDriver
        configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));

        // Specifies the default TypeHandler used by Enum.
        configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));

        // Specifies whether to call the setter (put) method of the map ping object when the value in the result set is null,
        // This is for Map.keySet() useful when initializing a dependency or null value.
        // Note that basic types (int, boolean, etc.) cannot be set to null.
        configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));

        // Whether to use the name in the method signature as the statement parameter name can reduce {@ link to some extent org.apache.ibatis . annotations.Param }Code of
        configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));

        // MyBatis returns null by default when all columns of the returned row are empty. When this setting is turned on, MyBatis returns an empty instance.
        // It should be noted that it also applies to nested result sets (collection s and association s)
        configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));

        // Specifies the prefix MyBatis added to the log name.
        configuration.setLogPrefix(props.getProperty("logPrefix"));

        // Specifies a class that provides a Configuration instance.
        // The returned Configuration instance is used to load the lazy load property value of the deserialized object.
        // This class must contain a signature method, static Configuration getConfiguration()
        configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    }

</details>

We have to say that there are a lot of codes in the settingsElement(Properties) method. Let's bear the nature one by one.

Configure automatic mapping behavior of mybatis

>Configure the processing behavior of Mybatis when it encounters unrecognized fields during automatic mapping

configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));

AutoMappingBehavior is the enumeration of policy definitions that define columns and fields for automatic mapping in mybatis. It has three parameters, NONE,PARTIAL,FULL Among them:

  • NONE, indicating that the automatic mapping function is disabled.
  • PARTIAL refers to local automatic mapping, which means that only the result sets without nested result sets are automatically mapped.
  • FULL, which represents the complete automatic mapping function. It can automatically map any complex result set, including the result set of nested result set.

When we define the collection or association attribute in the return parameter of ResultMap, the query operation is not a simple SQL. The specific result is actually a one to many complex set, where the one to many complex set is the nested result set. For example, we define Mapper as follows:

    <! -- classInfo and Student both have ID and name attributes, but it is not clear here that the result set of automatic mapping of Mybatis is adopted. >
    <! -- define the return resu lt of student class -- >
    <resultmap id="Student" type="*.*.*.Student">
    </resultmap>
    <!--
        Define the return result of class class
        The relationship between class and students is: one to many
    -->
    <resultmap id="ClassInfo" type="*.*.*.ClassInfo">
        <collection property="student" resultMap="Student" />
    </resultmap>

In this case, the query results corresponding to ClassInfo include a Student set, which is a nested result set.

In this way, only when our configuration ා automappingbehavior value is automappingbehavior ා full can we automatically assign the ID and Name values of the returned results of students to the corresponding fields of the Student object

Configure the processing behavior of Mybatis when it encounters unrecognized fields during automatic mapping

configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));

AutoMappingUnknownColumnBehavior is an enumeration class defined by Mybatis when a column or field cannot be processed (recognized) during automatic mapping. It provides a method called doAction to implement specific operations

    /**
     * An operation is performed when an unknown column (or unknown property type) of the automatic mapping target is detected.
     *
     * @param mappedStatement Mapping declaration statement
     * @param columnName      Field name
     * @param propertyName    Property name
     * @param propertyType    Field type. If the field is not null, the TypeHandler is not registered
     */
    public abstract void doAction(MappedStatement mappedStatement, String columnName, String propertyName, Class<!--?--> propertyType);

AutoMappingUnknownColumnBehavior has three modes, NONE is used by default

  • NONE, do nothing
  • WARNING, output WARNING log
  • FAILING, mapping fails and throws{ @link SqlSessionException}.

Enable L2 caching or not

configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));

cacheEnabled is the switch used by Mybatis to configure whether to enable all caches. It is true by default. In distributed applications, it is better to disable the secondary cache to avoid dirty reads.

Specifies the proxy factory for Mybatis lazy load objects

configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));

proxyFactory specifies the proxy factory used by Mybatis to create objects with delay loading capability. By default, JavassistProxyFactory is used

Enable lazy loading or not

configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));

Lazyloadenabled is the global switch for Mybatis to enable lazy loading. When on, all associated objects delay loading. The switch state of the item can be overridden by setting the fetchType property in a specific association.

Whether to allow all properties of the object to be loaded directly when the method is called

configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));

When on, calls to any method load all properties of the lazy load object. Otherwise, each property will be loaded on demand, and the default is false (refer to lazyLoadTriggerMethods)

Allow single statement to return multiple result sets

configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));

The default is true.

Use column label instead of column name

configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));

The default is true.

Allow JDBC to generate primary key automatically

configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));

This parameter is used to set whether the primary key is automatically generated. The default is false. If this parameter is true, the primary key will be automatically generated. Although some drivers are not compatible, they can still work normally.

Configure the default Sql executor for Mybatis

configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));

defaultExecutorType corresponds to ExecutorType enumeration class, which defines three types of Sql executors in Mybatis:

  • SIMPLE is a common executor, which creates a new preprocessing statement ({ @link java.sql.PreparedStatement});
  • The REUSE executor will REUSE the prepared statements;
  • The BATCH executor will reuse statements and perform BATCH updates.

The default is SIMPLE.

Configure Mybatis request timeout

configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));

This value determines the number of seconds Mybatis waits for the database to respond. By default, it never times out.

Configure the limit on the number of Mybatis request result sets

configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));

Set a prompt value for the fetchSize of the driven result set. This parameter can only be overridden in query settings.

Turn on the function of automatically converting underline to hump

configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));

When this function is enabled, Mybatis will automatically convert the JDBC class name from the typical underline naming method to the hump naming method of Java properties. The default value is false.

Whether to allow paging in nested statements (RowBounds)

configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));

Whether RowBouds is allowed to be used in nested result sets. The default value is false. Note!! False is allowed

>Rowbounds is the paging class of Mybatis. The specific usage will be given later.

Set the life cycle of Mybatis local cache

>Local caching is also known as L1 caching

configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));

LocalCacheScope is an enumeration of life cycle definitions of Mybatis local cache. It has two properties, which correspond to different life cycles of local cache.

  • SESSIO, in which case all queries executed in a session are cached
  • STATEMENT: the local session is only used for STATEMENT execution. Different calls to the same SqlSession will not share data

SESSION used by default

Configure the JDBC type used by default when the parameter is NULL when no JDBC type is specified for the parameter

configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));

When no JDBC type is specified for the parameter and the parameter is null, the default JDBC type is usually one of null, varchar and OTHER. Here, we will not list the instances of JdbcType enumeration. There are many contents in it. Here, the default is OTHER.

Configure the trigger method of Mybatis lazy loading

configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));

This parameter is mentioned in aggressiveLazyLoading. The two are usually used together. He has developed a trigger method for lazy loading, which is used to specify which methods of which objects trigger lazy loading once. The default value is: equals,clone,hashCode,toString.

Allow paging in nested statements (ResultHandler)

configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));

Set whether Mybaits allows use of ResultHandler in nested statements. Note!! If allowed, set to false. The default value is false

Mybatis Sql script language processor registry

configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));

Configure the global default SQL language processor of Mybatis. The default SQL language processor of Mybatis is XmlLanguage driver.

About the content of the language driver, we will give it in the extended content.

Configure the default converter for enumeration types

configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")))
   /**
     * Configure the default TypeHandler of enumeration type, and use EnumTypeHandler by default.
     *
     * @param typeHandler Type processor for handling enumeration types
     * @since 3.4.5
     */
    public void setDefaultEnumTypeHandler(Class<!--? extends TypeHandler--> typeHandler) {
        if (typeHandler != null) {
            // Gets the type processor registry and sets the default enumeration type processor
            getTypeHandlerRegistry().setDefaultEnumTypeHandler(typeHandler);
        }
    }

Gets the typeHandlerRegistry instance in Configuration

    /**
     * Get type processor registry
     */
    public TypeHandlerRegistry getTypeHandlerRegistry() {
        return typeHandlerRegistry;
    }

Configure the default enumeration type processor

 /**
     * Configure the default TypeHandler of enumeration type, and use EnumTypeHandler by default.
     *
     * @param typeHandler Type processor for handling enumeration types
     * @since 3.4.5
     */
    public void setDefaultEnumTypeHandler(Class<!--? extends TypeHandler--> typeHandler) {
        this.defaultEnumTypeHandler = typeHandler;
    }

TypeHandlerRegistry is the type conversion processor registry in Mybatis, which is mainly responsible for maintaining the TypeHandler used for java type and JDBC type conversion, It is an indispensable component in Mybatis. As a registry, it registers many default type conversion processors during initialization, which is convenient for us to use.

The defaultEnumTypeHandler property of TypeHandlerRegistry is used to record the default enumeration type handler.

The function of the parameter defaultEnumTypeHandler is to specify the value of typehandlerregistry ා defaultEnumTypeHandler, which is defaulted to EnumTypeHandler.

Whether to call the setter (put) method of the map ping object when the value in the result set is null

configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));

Set whether to call the Setter method corresponding to the property of the JAVA object when a value in the result set is null in Mybatis. The default value is false.

Whether to initialize an empty instance when the query content is empty

configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));

Set whether to initialize an empty instance when all return lines of the query result set of Mybatis are empty. The default value is false, that is, not used.

>It should be noted that when this function is enabled, it also works for nested results (collection and association).

Specify the MyBatis unified log name prefix

configuration.setLogPrefix(props.getProperty("logPrefix"));

Set the common prefix used by the logs in Mybatis.

Specify factory for Configuration

configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));

Specifies a class that provides a Configuration instance that is returned to load the lazy load property of the deserialized object.

>The class that configurationfactory points to must have a static Configuration getConfiguration() method definition

OK, the process of Configuration configuration based on settings element is over. The content of this part is relatively boring and tedious. Here, for these different fields Just have a general impression.

Pay attention to me and learn more together

Topics: Programming Mybatis JDBC Session SQL