整体架构
这只是对mybatis的一个逻辑划分。
接口层:通过SqlSession类提供对外接口,屏蔽了后续的复杂处理逻辑
处理器层:主要负责执行sql,返回结果
基础支撑层:对一些基础功能进行封装,为核心处理层提供支持
代码结构
mybatis的代码结构非常严谨。
Mybatis中的设计模式
设计模式在mybatis的应用:
SqlSession使用门面设计模式;
日志模块使用适配器模式;
数据源模块使用工厂模式;
数据库连接池使用策略模式;
缓存模块使用装饰器模式;
Executor模块使用模板方法模式;
Builder模块是用了创造者模式
Mapper接口使用了代理模式;
插件模块使用了责任练模式;
Mybatis 快速入门
public class MybatisTest extends BaseTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
String resource = "config/mybatis-config.xml";
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
// 1.读取mybatis配置文件创SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
@Test
// 测试自动映射以及下划线自动转化驼峰
public void quickStart() throws Exception {
// 2.获取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// 3.获取对应mapper
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
// 4.执行查询语句并返回结果
Person person = mapper.selectByPrimaryKey(1L);
System.out.println(person.toString());
}
}
}
Mybatis执行流程
new SqlSessionFactoryBuilder().build(inputStream);:读取mybatis配置文件构建SqlSessionFactory。sqlSessionFactory.openSession();:获取sqlSession资源sqlSession.getMapper(PersonMapper.class);:获取对应mappermapper.selectByPrimaryKey(1L);:执行查询语句并返回结果
上图是mybatis的执行流程,由此我们可以看出mybatis的核心类有4个:
SqlSessionFactoryBuilder,SqlSessionFactory,SqlSession,SQL Mapper
SqlSessionFactoryBuilde:读取配置信息(XML文件),创建SqlSessionFactory,建造者模式,方法级别生命周期;
SqlSessionFactory:创建Sqlsession,工厂单例模式,存在于程序的整个应用程序生命周期;
SqlSession:代表一次数据库连接,可以直接发送SQL执行,也可以通过调用Mapper访问数据库;线程不安全,要保证线程独享,方法级生命周期;
SQL Mapper:由一个Java接口和XML文件组成,包含了要执行的SQL语句和结果集映射规则。方法级别生命周期;
Mybatis核心流程三大阶段
mybatis的核心流程主要分为一下三个阶段:
初始化阶段:读取注解和xml中的配置信息,创建配置对象并完成各个模块的初始化工作;
代理阶段:封装iBatis编程模型,使用mapper接口开发;
数据读写阶段:通过sqlSession完成sql解析、参数映射、sql执行、结果的解析;
**源码注释:https://github.com/xiaolyuh/mybatis
来源:CSDN
作者:milaier
链接:https://blog.csdn.net/milaier/article/details/104098285