mybatis提供了两种配置文案案:基于Xml或基于Api
先看下mybatis提供的配置属性
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
基于Xml的初始化
首先是配置文件是xml格式,所以需要有专门的parser负责转换
核心职能由org.apache.ibatis.builder.xml.XMLConfigBuilder承担,该类负责将xml转换成org.apache.ibatis.session.Configuration。
Configuration中保存着全局的配置信息,包括静态配置的和动态生成的
parse的核心流程
private void parseConfiguration(XNode root) {
try {
// issue #117 read properties first
//属性有三个来源,具体查看 site/zh/configuration.html#properties
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
// VFS resource list, 目前支持两种实现,对JBoss作了特殊处理
loadCustomVfs(settings);
// 日志
loadCustomLogImpl(settings);
//
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
// 类型处理器
typeHandlerElement(root.evalNode("typeHandlers"));
// mapper 采集
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
整个处理流程的目的就是为了填充Configuration
基本Api的初始化
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
//基于Api创建配置对象,并按需配置
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);