MyBatis Alias and settings Settings

  • 2021-10-27 07:20:28
  • OfStack

MyBatis Alias and settings Settings

Alias (typeAliases) is a referential name. When the qualified name of the class is too long, you can specify alias to simplify the use. MyBatis is divided into two types: system-defined alias and custom alias. System-defined alias does not need us to specify again, and is registered through TypeAliasRegistry class.

Aliases in MyBatis are not case sensitive, and one instance of typeAliases is generated when the configuration file is parsed and then persisted in an Configuration object for a long time.

Next, configure the alias:

1. Introduce configuration in MyBatis Spring configuration file

Specify the configLocation property to configure it in the corresponding xml file, as follows:


    <!-- spring And MyBatis Perfect integration, no need mybatis Configuration mapping file for  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--  Automatic scanning mapping.xml Documents  -->
        <property name="mapperLocations" value="classpath:com.fc.mapper/*-sqlmap.xml"/>
        <!--  Configure  -->
        <property name="configLocation" value="classpath:sqlmap-alias.xml"/>
    </bean>

2. Configuration in sqlmap-alias. xml:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration>
    <!--  Open the mapping relationship between hump rules and underscores  -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
 
    <!--  Alias  -->
    <typeAliases>
        <typeAlias alias="USER" type="com.fc.bean.User" />
    </typeAliases> 
</configuration>

In < typeAliases > The alias corresponding to bean can be specified under the label, and multiple aliases of multiple classes can be added < typeAlias > Tags will do.

< settings > Is one of the most complex and important configurations of the MyBatis, but it works without configuration because the default configuration is already provided for the MyBatis,

If you need to make custom changes to the settings, you can add them in the configuration < settings > Label, as shown in the above example (Note that the settings in configuration are ordered, such as the label exchange order of settings and typeAliases mentioned above, and there will be an error prompt)

Specific attributes can refer to Configuration class, which can be passed in the configuration file < setting > Tag changes the default attribute value, mapUnderscoreToCamelCase is

Turn on the camel case (Automatic Hump Naming Convention) mapping, using the example:


<select id="queryUser" parameterType="java.util.Map" resultType="USER">
        SELECT
          id,
          real_name,
          sex sex,
          age age,
          login_name,
          login_password,
          create_time,
          update_time
        from temp_user
        <trim prefix="where" prefixOverrides="and">
            <if test="realName != null and realName != '' ">
                and real_name = #{realName}
            </if>
            <if test="loginName != null and loginName != '' ">
                and login_name = #{loginName}
            </if>
        </trim>
    </select>

3. The relatively complete setting settings and descriptions are as follows:


<!-- settings Settings  -->
    <settings>
        <!--  Mapper cache global switch, default true -->
        <setting name="cacheEnabled" value="true"/>
        <!--  Delayed loading global switch , Default false -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!--  Is the full load of an object with a delayed load property, and the default true -->
        <setting name="aggressiveLazyLoading" value="true"/>
        <!--  Allow Doc 1 Statement returns multiple result sets, and the default true -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!--  The column label replaces the column name, and the default true -->
        <setting name="useColumnLabel" value="true"/>
        <!--  Allow jdbc Support automatic generation of primary keys , Default false -->
        <setting name="useGeneratedKeys" value="false"/>
        <!--  Specify  MyBatis  How columns should be automatically mapped to fields or properties. 
            NONE  Indicates canceling automatic mapping; PARTIAL  Only result sets that do not have nested result set mappings defined are automatically mapped. 
            FULL  Automatically maps any complex result set (nested or not)  -->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <!--  Specifies the behavior of discovering unknown columns of automatic mapping targets, and the default NONE -->
        <setting name="autoMappingUnknownColumnBehavior" value="NONE"/>
        <!--  Specifies the default executor, SIMPLE/REUSE/BATCH -->
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!--  Set the timeout time, which is not set by default  -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!--  Get the quantity for the driven result set ( fetchSize ) Settings 1 Prompt values , Not set by default  -->
        <setting name="defaultFetchSize" value="1000"/>
        <!--  Paging in nested statements , Default false Indicates opening  -->
        <setting name="safeRowBoundsEnabled" value="false"/>
        <!--  Hump rule, default false -->
        <setting name="mapUnderscoreToCamelCase" value="false"/>
        <!--  Session opens local cache query mechanism , Other values STATEMENT Used in statement execution  -->
        <setting name="localCacheScope" value="SESSION"/>
        <!--  Is not specified for the parameter jdbc Type , Specifies for a null value jdbc Type  -->
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <!--  The method of the specified object triggers 1 Secondary delayed loading  -->
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
        <!--  Specify dynamic SQL Default language generated  -->
        <setting name="defaultScriptingLanguage" value="org.apache.ibatis.scripting.xmltags.XMLLanguageDriver"/>
        <!--  Specifies that when the value in the result set is null Object of the mapping object is called when setter ( map  Object is specified when the  put )  -->
        <setting name="callSettersOnNulls" value="false"/>
        <!--  Specify mybatis Prefix added to the log name, which is not set by default  -->
        <setting name="logPrefix" value="xxx_"/>
        <!--  Specify Mybatis Proxy Tools Used to Create Objects with Delay Load Capability ,3.3 Or above JAVASSIST -->
        <setting name="proxyFactory" value="CGLIB"/>
    </settings>

Usage and Explanation of MyBatis setting

Usage of setting


<!-- settings是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 -->  
    <settings>  
        <!-- 该配置影响的所有映射器中配置的缓存的全局开关。默认值true -->  
      <setting name="cacheEnabled" value="true"/>  
      <!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。默认值false  -->  
      <setting name="lazyLoadingEnabled" value="true"/>  
        <!-- 是否允许单1语句返回多结果集(需要兼容驱动)。 默认值true -->  
      <setting name="multipleResultSetsEnabled" value="true"/>  
      <!-- 使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。默认值true -->  
      <setting name="useColumnLabel" value="true"/>  
      <!-- 允许 JDBC 支持自动生成主键,需要驱动兼容。 如果设置为 true 则这个设置强制使用自动生成主键,尽管1些驱动不能兼容但仍可正常工作(比如 Derby)。 默认值false  -->  
      <setting name="useGeneratedKeys" value="false"/>  
     <!--  指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。 -->   
     <!-- 默认值PARTIAL -->  
      <setting name="autoMappingBehavior" value="PARTIAL"/>  
      <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>  
     <!--  配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。默认SIMPLE  -->  
      <setting name="defaultExecutorType" value="SIMPLE"/>  
      <!-- 设置超时时间,它决定驱动等待数据库响应的秒数。 -->  
      <setting name="defaultStatementTimeout" value="25"/>  
      <setting name="defaultFetchSize" value="100"/>  
      <!-- 允许在嵌套语句中使用分页(RowBounds)默认值False -->  
      <setting name="safeRowBoundsEnabled" value="false"/>  
      <!-- 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。  默认false -->  
      <setting name="mapUnderscoreToCamelCase" value="false"/>  
      <!-- MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。  
             默认值为 SESSION,这种情况下会缓存1个会话中执行的所有查询。  
            若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。  -->  
      <setting name="localCacheScope" value="SESSION"/>  
      <!-- 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用1般类型即可,比如 NULL、VARCHAR 或 OTHER。  -->  
      <setting name="jdbcTypeForNull" value="OTHER"/>  
    <!--   指定哪个对象的方法触发1次延迟加载。  -->  
      <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>  
    </settings>  

Specific explanation

Originated from official document handling, please correct me if there is any error. Thank you! In order to improve reading, it is divided into 4 tables.
设置名 描述 有效 默认值
cacheEnabled 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 true / false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 true / false true
aggressiveLazyLoading 开启时,任1方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods)。 true / false false false (在 3.4.1 及之前的版本中默认为 true)
multipleResultSetsEnabled 是否允许单个语句返回多结果集(需要数据库驱动支持)。 true / false true
useColumnLabel 使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。 true / false true
useGeneratedKeys 允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管1些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。 true / false false
autoMappingBehavior 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。 NONE, PARTIAL, FULL PARTIAL
autoMappingUnknownColumnBehavior 指定发现自动映射目标未知列(或未知属性类型)的行为。NONE: 不做任何反应。WARNING: 输出警告日志(‘org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN)。 FAILING: 映射失败 (抛出 SqlSessionException) NONE, WARNING, FAILING NONE
设置名 描述 有效 默认值
defaultExecutorType 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 SIMPLE REUSE BATCH SIMPLE
defaultStatementTimeout 设置超时时间,它决定数据库驱动等待数据库响应的秒数。 任意正整数 未设置 (null)
defaultFetchSize 为驱动的结果集获取数量(fetchSize)设置1个建议值。此参数只可以在查询设置中被覆盖。 任意正整数 未设置 (null)
defaultResultSetType 指定语句默认的滚动策略。(新增于 3.5.2) FORWARD_ONLY / SCROLL_SENSITIVE / SCROLL_INSENSITIVE / DEFAULT(等同于未设置) 未设置 (null)
safeRowBoundsEnabled 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。 true / false False
safeResultHandlerEnabled 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。 true / false True
mapUnderscoreToCamelCase 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 true / false false
localCacheScope MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存1个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。 SESSION /STATEMENT SESSION
jdbcTypeForNull 当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用1般类型即可,比如 NULL、VARCHAR 或 OTHER。 JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。 OTHER
设置名 描述 有效 默认值
lazyLoadTriggerMethods 指定对象的哪些方法触发1次延迟加载。 用逗号分隔的方法列表 equals,clone,hashCode,toString
defaultScriptingLanguage 指定动态 SQL 生成使用的默认脚本语言。 1个类型别名或全限定类名 org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler 指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5) 1个类型别名或全限定类名。 org.apache.ibatis.type.EnumTypeHandler
设置名 描述 有效 默认值
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 true / false false
returnInstanceForEmptyRow 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回1个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) true / false false
logPrefix 指定 MyBatis 增加到日志名称的前缀。 任何字符串 未设置
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J /LOG4J/ LOG4J2/JDK_LOGGING/COMMONS_LOGGING /STDOUT_LOGGING/NO_LOGGING 未设置
proxyFactory 指定 Mybatis 创建可延迟加载对象所用到的代理工具。 CGLIB JAVASSIST
vfsImpl 指定 VFS 的实现 自定义 VFS 的实现的类全限定名,以逗号分隔。 未设置
useActualParamName 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) true / false true
configurationFactory 指定1个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含1个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) 1个类型别名或完全限定类名。 未设置
shrinkWhitespacesInSql Removes extra whitespace characters from the SQL. Note that this also affects literal strings in SQL. (Since 3.5.5) true / false false

Related articles: