public static void main(String[] args) {
InputStream is = TestMybatis.class.getClassLoader().getResourceAsStream("mybatisconfig.xml");
//SqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//创建session
SqlSession session = sessionFactory.openSession();
String statement = "com.test.getDate";
Object date = session.selectOne(statement);
System.out.println(date);
}
示例代码如上 步骤总结:
1、创建SqlSessionFactory工厂 入参xml的stream流 可见会解析xml
2、通过工厂类创建SqlSession
3、通过SqlSession执行selectOne等方法 通过statementid获取到sql 并执行sql 获取返回值
org.apache.ibatis.session.SqlSessionFactoryBuilder.build(InputStream)
org.apache.ibatis.session.SqlSessionFactoryBuilder.build(InputStream, String, Properties)
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
//创建XMLConfigBuilder 对象 里面创建了XPathParser解析器
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());//parse解析 并build
} 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.
}
}
}
解析源码如下:
org.apache.ibatis.builder.xml.XMLConfigBuilder.parse()
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));//解析生成configuration对象
return configuration;
}
private void parseConfiguration(XNode root) {//就是通过根节点解析相关路径 然后设置到configuration对象中
try {
// issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
查看org.apache.ibatis.session.Configuration类的重要属性
protected Environment environment;//datasource环境
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);//mapper注册器
protected final InterceptorChain interceptorChain = new InterceptorChain();//拦截器
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
.conflictMessageProducer((savedValue, targetValue) ->
". please check " + savedValue.getResource() + " and " + targetValue.getResource());
//key:就是namespace+id组成的 value :MapperStatement就是所有的<select> <update>等标签解析出来的对象
protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");//缓存
protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");//结果集 <resultMap>标签集合
protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");//参数标签集合
总结1:mybatis会把所有的xml内容读取到Configuration对象中 等待后续使用
org.apache.ibatis.session.SqlSessionFactoryBuilder.build(Configuration)
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);//创建DefaultSqlSessionFactory对象 入参:Configuration对象
}
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession()
创建sqlSession
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();//拿到environment对象
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);//拿到数据库事务工厂
final Executor executor = configuration.newExecutor(tx, execType);//创建执行器
return new DefaultSqlSession(configuration, executor, autoCommit);//创建DefaultSqlSession 对象
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
创建执行器
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {//executorType默认为simple
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {//默认是SimpleExecutor
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {//默认开启 CachingExecutor里面持有代理对象SimpleExecutor 二级缓存
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);//拦截器执行 分页扩展点
return executor;
}
executor关系图如下
查看selectOne方法:
org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(String, Object)
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
List<T> list = this.selectList(statement, parameter);//执行的其实是selectList方法
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
public <E> List<E> selectList(String statement, Object parameter) {
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
return selectList(statement, parameter, rowBounds, Executor.NO_RESULT_HANDLER);
}
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);//拿到MapperdStatement对象 也就是sql对象
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);//通过执行器执行query
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
从二级缓存中查找
org.apache.ibatis.executor.CachingExecutor.query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {//缓存
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {//开启缓存
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {//缓存中没有
list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);//从代理类也就是SimpleExecutor的query方法
tcm.putObject(cache, key, list); // issue #578 and #116 放入缓存
}
return list;
}
}
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
org.apache.ibatis.executor.BaseExecutor.query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
//localCache本地缓存 一个事务会话中存在
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {//缓存中存在
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {//不存在则查数据库
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);//真正的查询方法
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
org.apache.ibatis.executor.SimpleExecutor.doQuery(MappedStatement, Object, RowBounds, ResultHandler, BoundSql)
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);//创建handler
stmt = prepareStatement(handler, ms.getStatementLog());//预编译
return handler.query(stmt, resultHandler);//执行query
} finally {
closeStatement(stmt);
}
}
org.apache.ibatis.session.Configuration.newStatementHandler(Executor, MappedStatement, Object, RowBounds, ResultHandler, BoundSql)
创建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);//创建RoutingStatementHandler
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);//拦截器执行
return statementHandler;
}
org.apache.ibatis.executor.statement.RoutingStatementHandler.RoutingStatementHandler(Executor, MappedStatement, Object, RowBounds, ResultHandler, BoundSql)
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
switch (ms.getStatementType()) {//默认是PREPARE
case STATEMENT:
delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case PREPARED:
delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case CALLABLE:
delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
default:
throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
}
}
org.apache.ibatis.executor.statement.BaseStatementHandler.BaseStatementHandler(Executor, MappedStatement, Object, RowBounds, ResultHandler, BoundSql)
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
this.configuration = mappedStatement.getConfiguration();
this.executor = executor;
this.mappedStatement = mappedStatement;
this.rowBounds = rowBounds;
this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
this.objectFactory = configuration.getObjectFactory();
if (boundSql == null) { // issue #435, get the key before calculating the statement
generateKeys(parameterObject);
boundSql = mappedStatement.getBoundSql(parameterObject);
}
this.boundSql = boundSql;
this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);//创建参数执行器
this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);//创建结果集执行器
}
org.apache.ibatis.executor.SimpleExecutor.prepareStatement(StatementHandler, Log)
通过内置的typeHandler 进行setParameter操作
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);//拿到jdbc connection
stmt = handler.prepare(connection, transaction.getTimeout());//sql预编译
handler.parameterize(stmt);//setPameter操作
return stmt;
}
org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(PreparedStatement)
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
typeHandler.setParameter(ps, i + 1, value, jdbcType);//通过typeHandler设置参数
} catch (TypeException | SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
org.apache.ibatis.executor.statement.PreparedStatementHandler.query(Statement, ResultHandler) 执行query操作
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();//jdbc的execute操作
return resultSetHandler.handleResultSets(ps);//结果集设置
}
org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(Statement)
public List<Object> handleResultSets(Statement stmt) throws SQLException {
ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
ResultSetWrapper rsw = getFirstResultSet(stmt);
List<ResultMap> resultMaps = mappedStatement.getResultMaps();//拿到resultMap结果集进行设置
int resultMapCount = resultMaps.size();
validateResultMapsCount(rsw, resultMapCount);
while (rsw != null && resultMapCount > resultSetCount) {
ResultMap resultMap = resultMaps.get(resultSetCount);
handleResultSet(rsw, resultMap, multipleResults, null);
rsw = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
String[] resultSets = mappedStatement.getResultSets();//
if (resultSets != null) {
while (rsw != null && resultSetCount < resultSets.length) {
ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
if (parentMapping != null) {
String nestedResultMapId = parentMapping.getNestedResultMapId();
ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
handleResultSet(rsw, resultMap, null, parentMapping);
}
rsw = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
}
return collapseSingleResultList(multipleResults);
}
SimpleExecutor总结如下:
1、拿到Configuration对象
2、创建StatementHandler:RoutingStatementHandler 同时创建了代理类PreparedStatementHandler
3、同时创建了ParameterHandler以及ResultSetHandler
接下来就是jdbc的操作步骤
4、拿到jdbc连接connection
5、通过PreparedStatementHandler进行prepareStatement操作
6、通过ParameterHandler进行setParameter
7、execute操作执行sql 拿到ResultSet结果集
8、通过ResultSetHandler处理结果集 转换成对象