mybatis源码分析

Mybatis的初始化过程

1 mybatis使用代码

mybatis官网文档

主要流程图
流程图

    public class MyBatisMain {
    public static void main(String[] args) {
        // 第一阶段:MyBatis的初始化阶段,配置各项属性
        String resource = "conf/mapperTest.xml";
        // 得到配置文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
                
        //第二阶段发出数据库请求操作
        try (SqlSession session = sqlSessionFactory.openSession()) {
            Student student = session.selectOne("mapper/mapperSql.getUserById", 2);
            System.out.println(student.toString());
        }
    }
}

主体代码分为两部分:

  • 分是通过配置文件将mybatis中的各个内置注册列表填充,然后获取SqlsessionFactory。

  • 执行与数据库相关的操作,包括sql语句转换,返回值处理等。

2 mybatis的流程解析

创建XMLConfigBuilder --> 用其解析XML文件获取Config --> SqlSessionFactory使用Config获取sqlSession

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
/**
   * 根据配置信息建造一个SqlSessionFactory对象
   * @param config 配置信息
   * @return SqlSessionFactory对象
   */
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值