Mybatis参考资料,核心组件及SqlSession四大对象
核心组件
- SqlSessionFactoryBuilder
(1)作用:根据配置信息或者代码来生成SqlSessionFactory
(2)实现原理:SqlSessionFactoryBuilder类负责构建SqlSessionFactory,通过源码分析,该类下提供了多个build的重载方法。其实这些方法可以归结为一个签名的方法,但是这些方法的参数不统一,为了方便调用,故重载了多个方法
如图可分为3种形式,Redaer,和InputStream 为通过读取XML文件,Configuration 为采用Java代码方式茶创建SqlSessionFactory,
- SqlSessionFactory
(1)作用:生产SqlSession会话
(2)实例代码:sqlSession = sqlSessionFactory.openSession();
- SqlSession
获取映射器,让映射器通过命名空间和方法名称找到对应的SQL,发送给数据库执行后返回结果;2)通过update、insert、select、delete等方法,带上SQL的id来操作在XML中配置好的SQL,从而完成工作,与此同时它也支持事务,通过commit、rollback方法提交或者回滚事务。
- SqlMapper
SqlSession四大对象:
- ParameterHandler //处理sql的参数对象
- ResultSetHandler //处理sql的返回结果集
- StatementHandler //数据库的处理对象
- Executor //Mybatis的执行器
重点类:
Configuration.java
//ParameterHandler 处理sql的参数对象
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
//包装参数插件
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
//ResultSetHandler 处理sql的返回结果集
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
//包装返回结果插件
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
//StatementHandler 数据库的处理对象
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
//包装数据库执行sql插件
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction) {
//创建Mybatis的执行器:Executor
return newExecutor(transaction, defaultExecutorType);
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
//mybatis支持的三种执行器:batch、reuse、simple,其中默认支持的是simple
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
//包装执行器插件
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}