Mybatis 文档篇 2.5:Configuration 之
1 Configuration Structure
- properties
- settings
- typeAliases
- typeHandlers
- objectFactory
- plugins
-
environments
- environment
- transactionManager
- dataSource
- environment
- databaseIdProvider
- mappers
2 ObjectFactory
Each time MyBatis creates a new instance of a result object, it uses an ObjectFactory instance to do so.
作用:每次 MyBatis 创建一个结果对象的新实例时,它都会使用一个 ObjectFactory 实例来完成(通过反射创建结果对象实例)。
2.1 默认的 ObjectFactory
The default ObjectFactory does little more than instantiate the target class with a default constructor, or a parameterized constructor if parameter mappings exist.
默认的 ObjectFactory 仅仅是实例化目标类,通过一个默认的构造器实例化,或者在参数映射存在的情况下通过一个参数化构造器实例化。
2.2 自定义 ObjectFactory
If you want to override the default behaviour of the ObjectFactory, you can create your own.
如果你想要覆盖 ObjectFactory 默认的行为,你可以创建你自己的 ObjectFactory。
// ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
public Object create(Class type) {
return super.create(type);
}
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
return super.create(type, constructorArgTypes, constructorArgs);
}
public void setProperties(Properties properties) {
super.setProperties(properties);
}
public <T> boolean isCollection(Class<T> type) {
return Collection.class.isAssignableFrom(type);
}
}
<!-- mybatis-config.xml -->
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
<property name="someProperty" value="100"/>
</objectFactory>
The ObjectFactory interface is very simple. It contains two create methods, one to deal with the default constructor, and the other to deal with parameterized constructors.
ObjectFactory 接口非常简单。它包含了两个 create 方法,一个用来处理默认构造方法,另一个用来处理带参数的构造方法。
Finally, the setProperties method can be used to configure the ObjectFactory. Properties defined within the body of the objectFactory element will be passed to the setProperties method after initialization of your ObjectFactory instance.
setProperties 方法用来配置 ObjectFactory。定义在 objectFactory 元素下 properties 将会在 ObjectFactory 实例初始化后传递给 setProperties 方法。
最后
说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!
当前版本:mybatis-3.5.0
官网文档:MyBatis
官网翻译:MyBatis 简体中文
项目实践:MyBatis Learn