前言 |
上一遍文章《一起来学习Mybatis-入门》,简单的搭建了一个使用Mybatis框架的应用,可以看做是学习Mybatis的初体验。那么今天主要来分享一下Mybatis是如何初始化的,它的配置项又有哪些,重点来分析一下源码。
分析 |
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 对象为中心的,而SqlSessionFactory 对象可以通过 SqlSessionFactoryBuilder 获得,所以来看看 SqlSessionFactoryBuilder 类里到底包含哪些东西。
SqlSessionFactoryBuilder
打开Mybatis源码文件,找到 org.apache.ibatis.session 包中的 SqlSessionFactoryBuilder 类,可以发现只有一个 build() 方法,返回值为 SqlSessionFactory,但是进行了8次重载,为了匹配不同的参数类型及个数。
虽然看起来有很多方法,第一眼有点头大,但是仔细观察后可以发现,这些方法大致可以分为三类:
Reader-Java.io中的字符流读取类
InputStream-Java.io中的字节流读取类
Configuration-org.apache.ibatis.session包中的一个配置信息类
继续往下看,参数为Reader、InputStream的build方法最后都是调用参数为Configuration的build方法。
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
不难理解,创建一个SqlSessionFactory 对象可以有两种方法。一:直接在类中硬编码,添加基本的配置信息,操作简单,容易理解,但是不灵活,每次修改后都需要重新编译。二:把配置信息放置到XML文件中,程序每次启动后自动读取并转化为Configuration 对象用于Mybatis初始化。
无论 SqlSessionFactory是不是由XML配置并构建,最后的配置信息都会转化为 Configuration 对象,所以还是来看下Mybatis是如何解析XML的,XML文件中又包含哪些配置项。
XMLConfigBuilder
Reader和InputStream对象都是由XMLConfigBuilder来解析的。
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
打开 XMLConfigBuilder 类,经过几次调用,发现了是类中的 parseConfiguration 方法来解析XML文件中相对应的元素。
由此,可以看出在Mybatis配置文件的根元素<configuration>下,有11个二级元素:properties、settings、typeAliases、plugins、objectFactory、objectWrapperFactory、reflectorFactory、environments、databaseIdProvider、typeHandlers、mappers。
小结 |
可以使用两种方式来初始化Mybatis:
- 使用XML配置文件构建
//用字节流的方式读取配置文件
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- 不使用XML配置文件构建
//获取数据源
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
//初始化事务工厂类
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
后面重点分析Mybatis XML配置文件的各个元素,看看它们分别支持哪些功能。