mybatis (四) 运行原理
作者:互联网
运行原理
简介
先来看一段简单的mybatis代码:
/**
* SqlSession非线程安全 测试可以这样使用 切记开发环境不可以这样
* 开发环境必须从sqlSessionFactory获取
*/
SqlSession sqlSession;
DeptMapper mapper;
@Before
public void sqlSession() throws IOException {
String resource = "mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(DeptMapper.class);
}
@After
public void close() {
sqlSession.close();
}
@Test
public void findDeptPlusByid() {
DeptPlus deptPlusByid = mapper.findDeptPlusByid(2L);
System.out.println(deptPlusByid);
}
本文适合写一个简单的demo进行debug阅读本文。
大致整理了一下mybatis的执行流程:
mybatis架构设计:
一、sqlSessionFactory
二、sqlSession
三、 getMapper
获取mapper:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}
MapperProxyFactory:
public T newInstance(SqlSession sqlSession) {
MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
return this.newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
}
四、mybatis查询流程
五、运行流程总结
- 根据配置文件(全局,sql映射)初始化出Configuration对象
- 创建一个DefaultSqlSession对象,它里面包含Configuration以及Executor(根据全局配置文件中的defaultExecutorType创建出对应的Executor)
- DefaultSqlSession.getMapper():拿到Mapper接口对应的MapperProxy;
- MapperProxy里面有(DefaultSqlSession);
- 执行增删改查方法:
- 调用DefaultSqlSession的增删改查(Executor);
- 会创建一个StatementHandler对象。同时也会创建出ParameterHandler和ResultSetHandler)
- 调用StatementHandler预编译参数以及设置参数值,使用ParameterHandler来给sql设置参数
- 调用StatementHandler的增删改查方法;
- ResultSetHandler封装结果
注意:四大对象每个创建的时候都有一个interceptorChain.pluginAll(parameterHandler);
标签:mapper,getMapper,sqlSession,new,mybatis,原理,public,运行 来源: https://blog.csdn.net/weixin_44032502/article/details/113717970