02 Mybatis应用篇---XML配置之properties 属性和settings 设置

MyBatis的配置文件包含了MyBatis设置(settings),属性(properties)等信息。文档的顶层结构如下:
configuration 配置
        * properties 属性
        * settings 设置
        * typeAliases 类型命名
        * typeHandlers 类型处理器
        * objectFactory 对象工厂
        * plugins 插件
        * environments 环境
            * environment 环境变量
                * transactionManager 事务管理器
                * dataSource 数据源
        * databaseIdProvider 数据库厂商标识
        * mappers 映射器

properties:
     这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。例如:

<!-- 指定properties配置文件, 我这里面配置的是数据库相关 -->
<properties  resource ="dbconfig.properties" >
    <property  name ="username"  value ="root1" />
</properties>

     其中的属性就可以在整个配置文件中使用来替换需要动态配置的属性值。比如:

<dataSource  type ="POOLED" >
    <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
    <property  name ="driver"  value ="${driver}" />
    <property  name ="url"  value ="${url}" />
    <property  name ="username"  value ="${username}" />
    <property  name ="password"  value ="${password}" />
</dataSource>

     username 将会由properties元素中设置的相应值来替换,password,url,driver属相将会由dbconfig.properties文件中对应的值来替换。
     属性也可以被传递到  SqlSessionFactoryBuilder().build()方法中:例如:

Properties prop =  new Properties() ;
prop.setProperty( "username" , "root") ;
sqlSessionFactory =  new SqlSessionFactoryBuilder().build(stream ,prop) ;

源码(SqlSessionFactoryBuilder):

public SqlSessionFactory  build(Reader reader Properties properties) {
  return build(reader , null, properties) ;
}
public SqlSessionFactory  build(InputStream inputStream Properties properties) {
  return build(inputStream , null, properties) ;
}

如果属性在不只一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:
     ① 在 properties 元素体内指定的属性首先被读取。
     ② 然后根据 properties 元素中的 resource 属性读取类路径下属性文件或根据 url 属性指定的路径读取属性文件,并覆盖已读取的同名属性。
     ③ 最后读取作为方法参数传递的属性,并覆盖已读取的同名属性。
因此,优先级自高向低顺序是③②① 。通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的是 properties 属性中指定的属性。

settings:
     这是MyBatis中极为重要的调整设置,它们会改变MyBatis的运行时行为。
     参考官方解释如下:

设置参数描述有效值默认值
cacheEnabled 该配置影响的所有映射器中配置的缓存的全局开关。 true | false true
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。 true | false false
aggressiveLazyLoading When enabled, any method call will load all the lazy properties of the object. Otherwise, each property is loaded on demand (see also lazyLoadTriggerMethods). true | false false (true in ≤3.4.1)
multipleResultSetsEnabled 是否允许单一语句返回多结果集(需要兼容驱动)。 true | false true
useColumnLabel 使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。 true | false true
useGeneratedKeys 允许 JDBC 支持自动生成主键,需要驱动兼容。 如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。 true | false False
autoMappingBehavior 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。 NONE, PARTIAL, FULL PARTIAL
autoMappingUnknownColumnBehavior Specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target.
  • NONE: Do nothing
  • WARNING: Output warning log (The log level of 'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior'must be set to WARN)
  • FAILING: Fail mapping (Throw SqlSessionException)
NONE, WARNING, FAILING NONE
defaultExecutorType 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。 SIMPLE REUSE BATCH SIMPLE
defaultStatementTimeout 设置超时时间,它决定驱动等待数据库响应的秒数。 任意正整数 Not Set (null)
defaultFetchSize 为驱动的结果集获取数量(fetchSize)设置一个提示值。此参数只可以在查询设置中被覆盖。 任意正整数 Not Set (null)
safeRowBoundsEnabled 允许在嵌套语句中使用分页(RowBounds)。 If allow, set the false. true | false False
safeResultHandlerEnabled 允许在嵌套语句中使用分页(ResultHandler)。 If allow, set the false. true | false True
mapUnderscoreToCamelCase 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 true | false False
localCacheScope MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。 SESSION | STATEMENT SESSION
jdbcTypeForNull 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER OTHER
lazyLoadTriggerMethods 指定哪个对象的方法触发一次延迟加载。 A method name list separated by commas equals,clone,hashCode,toString
defaultScriptingLanguage 指定动态 SQL 生成的默认语言。 A type alias or fully qualified class name. org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意基本类型(int、boolean等)是不能设置成 null 的。 true | false false
returnInstanceForEmptyRow MyBatis, by default, returns null when all the columns of a returned row are NULL. When this setting is enabled, MyBatis returns an empty instance instead. Note that it is also applied to nested results (i.e. collectioin and association). Since: 3.4.2 true | false false
logPrefix 指定 MyBatis 增加到日志名称的前缀。 Any String Not set
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
proxyFactory 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。 CGLIB | JAVASSIST JAVASSIST (MyBatis 3.3 or above)
vfsImpl 指定VFS的实现 自定义VFS的实现的类全限定名,以逗号分隔。 Not set
useActualParamName 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的工程必须采用Java 8编译,并且加上-parameters选项。(从3.4.1开始) true | false true
     一个完整的setting元素实例如下:
<settings>
 
<setting   name = "cacheEnabled"   value = "true" />
 
<setting   name = "lazyLoadingEnabled"   value = "true" />
 
<setting   name = "multipleResultSetsEnabled"   value = "true" />
 
<setting   name = "useColumnLabel"   value = "true" />
 
<setting   name = "useGeneratedKeys"   value = "false" />
 
<setting   name = "autoMappingBehavior"   value = "PARTIAL" />
 
<setting   name = "autoMappingUnknownColumnBehavior"   value = "WARNING" />
 
<setting   name = "defaultExecutorType"   value = "SIMPLE" />
 
<setting   name = "defaultStatementTimeout"   value = "25" />
 
<setting   name = "defaultFetchSize"   value = "100" />
 
<setting   name = "safeRowBoundsEnabled"   value = "false" />
 
<setting   name = "mapUnderscoreToCamelCase"   value = "false" />
 
<setting   name = "localCacheScope"   value = "SESSION" />
  <setting   name = "jdbcTypeForNull"   value = "OTHER" />
  <setting   name = "lazyLoadTriggerMethods"   value = "equals,clone,hashCode,toString" />
</settings>
源码(XMLConfigBuilder):
private void  settingsElement(Properties props)  throws Exception {
  configuration.setAutoMappingBehavior(AutoMappingBehavior. valueOf(props.getProperty( "autoMappingBehavior" "PARTIAL"))) ;
  configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior. valueOf(props.getProperty( "autoMappingUnknownColumnBehavior" "NONE"))) ;
  configuration.setCacheEnabled(booleanValueOf(props.getProperty( "cacheEnabled") , true)) ;
  configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty( "proxyFactory"))) ;
  configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty( "lazyLoadingEnabled") , false)) ;
  configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty( "aggressiveLazyLoading") , true)) ;
  configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty( "multipleResultSetsEnabled") , true)) ;
  configuration.setUseColumnLabel(booleanValueOf(props.getProperty( "useColumnLabel") , true)) ;
  configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty( "useGeneratedKeys") , false)) ;
  configuration.setDefaultExecutorType(ExecutorType. valueOf(props.getProperty( "defaultExecutorType" "SIMPLE"))) ;
  configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty( "defaultStatementTimeout") , null)) ;
  configuration.setDefaultFetchSize(integerValueOf(props.getProperty( "defaultFetchSize") , null)) ;
  configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty( "mapUnderscoreToCamelCase") , false)) ;
  configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty( "safeRowBoundsEnabled") , false)) ;
  configuration.setLocalCacheScope(LocalCacheScope. valueOf(props.getProperty( "localCacheScope" "SESSION"))) ;
  configuration.setJdbcTypeForNull(JdbcType. valueOf(props.getProperty( "jdbcTypeForNull" "OTHER"))) ;
  configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty( "lazyLoadTriggerMethods") "equals,clone,hashCode,toString")) ;
  configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty( "safeResultHandlerEnabled") , true)) ;
  configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty( "defaultScriptingLanguage"))) ;
  configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty( "callSettersOnNulls") , false)) ;
  configuration.setLogPrefix(props.getProperty( "logPrefix")) ;
  configuration.setLogImpl(resolveClass(props.getProperty( "logImpl"))) ;
  configuration.setConfigurationFactory(resolveClass(props.getProperty( "configurationFactory"))) ;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值