当我们在调用mybatis mapper的接口时发生了点什么事呢 简单的跟着源码看了看
@Service("userService") public class UserServiceImpl implements IUserService { //UserMapper是我的接口,mybatis给它生成一个动态代理 @Resource private UserMapper userMapper; public User getUserById(int userId) { // TODO Auto-generated method stub //执行我们接口所对应的sql return this.userMapper.selectByPrimaryKey(userId); } }
我们查看一下调用堆栈
我们直接到invoke中看一下发生了什么事
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); }//查看是否有缓存 final MapperMethod mapperMethod = cachedMapperMethod(method);//继续执行 return mapperMethod.execute(sqlSession, args); }
我们接着进execute看一下代码
public Object execute(SqlSession sqlSession, Object[] args) { Object result; switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: if (method.returnsVoid() && method.hasResultHandler()) { executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { result = executeForCursor(sqlSession, args); } else { //把输入参数转换一下 Object param = method.convertArgsToSqlCommandParam(args); //我们查询最后会走到这里 result = sqlSession.selectOne(command.getName(), param); } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; }
根据我们需求不同 会case到不同的地方,我们跟的是select 所以最后会走到sqlSession.selectOne部分,接着进入代码
publicT selectOne(String statement, Object parameter) { return this.sqlSessionProxy. selectOne(statement, parameter); }
我们可以看出sqlSessionProxy也是一个代理对象,它代理的是谁呢,是我们的DefaultSqlSession 我们进入DefaultSqlSession查看
//我们通过动态代理 会走到这里 @Override publicT selectOne(String statement, Object parameter) { // Popular vote was to return null on 0 results and throw exception on too many. //然后会调用selectList List list = this. selectList(statement, parameter); 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; } }
进入selectList
@Override publicList selectList(String statement, Object parameter, RowBounds rowBounds) { try {//这个是不是特别熟悉,我们在加载xml的时候,会存储到这个里面 MappedStatement ms = configuration.getMappedStatement(statement);//执行sql return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
我们会通过configuration.getMappedStatement(statement);把xml跟sql相关的 数据取出来,然后我们进入executor.query
@Override publicList query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { //获取sql BoundSql boundSql = ms.getBoundSql(parameterObject); //创建缓存 CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql); return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
boundSql 中存着的就是我们真实的sql(下图),createCacheKey我猜测是创建查询缓存
然后我们进入query函数
publicList 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, parameterObject, boundSql); @SuppressWarnings("unchecked") List list = (List ) tcm.getObject(cache, key); if (list == null) { list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); // issue #578 and #116 } return list; } } return delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
我们可以看到,最初是查询缓存,如果没有的话 ,我们又会进入一个query
publicList 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 list; try { queryStack++; list = resultHandler == null ? (List ) localCache.getObject(key) : null; if (list != null) { handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); } else { //从这进入queryFromDatabase数据库查询 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; }
queryFromDatabase
privateList queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { List 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; }
我们会先把缓存的key存起来,然后执行doQuery
publicList 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); stmt = prepareStatement(handler, ms.getStatementLog()); return handler. query(stmt, resultHandler); } finally { closeStatement(stmt); } }
获取configuration 之后 执行handler.query
publicList query(Statement statement, ResultHandler resultHandler) throws SQLException { return delegate. query(statement, resultHandler); }
@Override publicList query(Statement statement, ResultHandler resultHandler) throws SQLException { PreparedStatement ps = (PreparedStatement) statement; ps.execute(); return resultSetHandler. handleResultSets(ps); }
执行到这里 是不是看到jdbc的执行语句了,没错 就是PreparedStatement !
这篇简单的说了一下mybatis的执行过程,如果有不对之处敬请指出,关于xml的加载还有动态代理的问题 请看我其他文章