在使用mybatis的第一步其实就是加载配置信息,生成SqlSessionFactory初始化Configuration对象。
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
sessionFactory.setConfigLocation(configLocation);
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String[] mapperLocation = mapperLocations.split(",");
List<Resource> lisResource = new ArrayList<Resource>();
for (String s : mapperLocation) {
lisResource.addAll(Arrays.asList(resolver.getResources(s)));
}
sessionFactory.setMapperLocations(lisResource.toArray(new Resource[mapperLocation.length]));
return sessionFactory.getObject();
这里我们主要是,根据SqlSessionFactoryBean,这是一个FactoryBean,我们会在这个对象里面设置数据库DataSource,配置文件路径ConfigLocation,所有mapper.xml的文件路径,最后根根据getObject去初始化一个SqlSessionFactory。
public SqlSessionFactory getObject() throws Exception {
//判断是否已经生成了SqlSessionFactory
//如果没有的话初始化,有的话直接返回
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
我们看一下具体的初始化方法:
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Mybatis源码解析:SqlsessionFactory生成

本文深入探讨Mybatis的SqlsessionFactory初始化过程。从SqlSessionFactoryBean出发,详细解释如何设置DataSource、ConfigLocation及mapper.xml路径,最终通过SqlSessionFactoryBuilder生成DefaultSqlSessionFactory实例。
最低0.47元/天 解锁文章
522

被折叠的 条评论
为什么被折叠?



