mybatis学习分享1

Mybatis工作原理

一、系统启动阶段

  1. SqlSessionFactoryBean中初始化sqlSessionFactoryBuilder
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
  1. afterPropertiesSet方法中构建SqlSessionFactory
public void afterPropertiesSet() throws Exception {
	......
	this.sqlSessionFactory = this.buildSqlSessionFactory();
}
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
	// Configuration对象的生成
	......
	return this.sqlSessionFactoryBuilder.build(configuration);
}
public SqlSessionFactory build(Configuration config) {
	return new DefaultSqlSessionFactory(config);
}

从上面的代码可以看出,SqlSessionFactory仅仅是new DefaultSqlSessionFactory(config),所以其中最重要的还是Configuration对象的生成。
Configuration 对象的生成:
(1)读取mybatis-config.xml,将mybatis的运行环境等信息(例如数据库连接信息)放到Configuration对象中。
(2)读取mapper.xml,构建MappedStatement对象放到Configuration对象中。
mapper.xml文件中的一个<select | update | delete | insert>标签对应一个MappedStatement对象,MappedStatement对象封装了sql语句、参数、结果、sql类型(select|update|delete|insert)等信息。MappedStatement的id是mapper接口全路径名+方法名。
MappedStatement对象在Configuration中以Map形式存在,key就是MappedStatement对象的id,value是MappedStatement对象:

protected final Map<String, MappedStatement> mappedStatements;

二、查询阶段

  1. 开启会话
    调用DefaultSqlSessionFactory中的openSession()方法开启会话,获得SqlSession对象。
  2. SqlSession对象根据mapper接口全路径名+方法名获取到MappedStatement对象,将查询任务委托给执行器Executor
  3. 执行器Executor主要负责维护一级缓存和二级缓存,并提供事务管理的相关操作,它会将数据库相关操作委托给 StatementHandler完成。
  4. StatementHandler使用PreparedStatement对象去执行sql,并处理返回结果:
PreparedStatement ps = (PreparedStatement)statement;
ps.execute();
return this.resultSetHandler.handleResultSets(ps);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值