Mybatis学习系列(二):源码解析—SqlsessionFactory

本文深入探讨Mybatis的SqlsessionFactory初始化过程。从SqlSessionFactoryBean出发,详细解释如何设置DataSource、ConfigLocation及mapper.xml路径,最终通过SqlSessionFactoryBuilder生成DefaultSqlSessionFactory实例。
摘要由CSDN通过智能技术生成

在使用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 {

    Configurati
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值