Go deep into mybatis source code - execution process

Don't talk at night 2022-02-13 07:25:58 阅读数:832

deep mybatis source code execution


The last analysis Mybatis How to load parsing XML Of documents , This article is followed by , analysis Mybatis The remaining two stages of : Agent encapsulation and SQL perform .


Agent encapsulation

Mybatis There are two ways to call Mapper Interface :

private static SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
// The first one is 
try (SqlSession session = sqlMapper.openSession(TransactionIsolationLevel.SERIALIZABLE)) {

Blog blog = session.selectOne("org.apache.ibatis.domain.blog.mappers.BlogMapper.selectBlogWithPostsUsingSubSelect", 1);
// The second kind 
try (SqlSession session = sqlMapper.openSession()) {

AuthorMapper mapper = session.getMapper(AuthorMapper.class);
Author author = mapper.selectAuthor(101);

From the above code, we can see that no matter which one, we must first create SqlSessionFactory object , Then get... Through this object SqlSession object . In previous versions, you can only call... Through the addition, deletion and modification of this object Mapper Interface , It's obviously not readable in this way , Difficult to maintain , It's also complicated to write , So later, Google began to maintain Mybatis after , Repackaging provides a second way to directly call Mapper Interface . However, in essence, the second is implemented on the basis of the first , So let's focus on the second one , Enter into getMapper Method :

 public <T> T getMapper(Class<T> type) {

return configuration.<T>getMapper(type, this);
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {

return mapperRegistry.getMapper(type, sqlSession);
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {

final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {

throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
try {

return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {

throw new BindingException("Error getting mapper instance. Cause: " + e, e);

mapperRegistry The object was analyzed in the last article , It's parsing xml Medium mapper When the node is registered , And this object caches Mapper Interface and corresponding The agent factory Mapping , therefore getMapper The core of is to create proxy objects through this factory :

 public T newInstance(SqlSession sqlSession) {

// Each call creates a new MapperProxy object 
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);

And then through Mapper When the interface is called, it will first call MapperProxy Of invoke Method :

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

try {

if (Object.class.equals(method.getDeclaringClass())) {
// If it is Object The method itself is not enhanced 
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {

return invokeDefaultMethod(proxy, method, args);
} catch (Throwable t) {

throw ExceptionUtil.unwrapThrowable(t);
// From the cache mapperMethod object , If it's not in the cache , Then create a , And add it to the cache 
final MapperMethod mapperMethod = cachedMapperMethod(method);
// call execute Method execution sql
return mapperMethod.execute(sqlSession, args);
private MapperMethod cachedMapperMethod(Method method) {

return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));

First get... From the cache MapperMethod object , This object encapsulates SQL Type of statement 、 Namespace 、 Enter the reference 、 Return information such as type , And then through its execute Method call SqlSession The method of adding, deleting, checking and modifying :

 public Object execute(SqlSession sqlSession, Object[] args) {

Object result;
// according to sql The statement type and the parameter selection returned by the interface call different 
switch (command.getType()) {

case INSERT: {

Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
case UPDATE: {

Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
case DELETE: {

Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
// The return value is void
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
// The return value is set or array 
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
// The return value is map
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
// The return value is cursor 
result = executeForCursor(sqlSession, args);
} else {
// Handle the case that is returned as a single object 
// Parse the parameters through the parameter parser 
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {

result = OptionalUtil.ofNullable(result);
case FLUSH:
result = sqlSession.flushStatements();
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;

As mentioned above SqlSession Essentially, Facade mode The embodiment of , It is essentially through Executor The implementation of the actuator component , All methods of accessing the database are defined in this component :

 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {

try {

// from configuration Get the sql Statement configuration information 
MappedStatement ms = configuration.getMappedStatement(statement);
// adopt executor Execute statement , And return the specified result set 
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {

throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {


and Executor Object is getting SqlSession Created when :

 public SqlSession openSession() {

return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {

Transaction tx = null;
try {

// obtain mybatis In the configuration file environment object 
final Environment environment = configuration.getEnvironment();
// from environment obtain transactionFactory object 
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
// Create a transaction object 
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// Create from configuration executor
final Executor executor = configuration.newExecutor(tx, execType);
// establish DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {

closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {


TransactionFactory Are we in xml Configured in transactionManager attribute , The optional properties are JDBC and Managed, Then create the transaction object according to our configuration , Then you create Executor object .

 public Executor newExecutor(Transaction transaction, ExecutorType executorType) {

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 {

executor = new SimpleExecutor(this, transaction);
// If there is <cache> node , Through ornaments , Ability to add L2 cache 
if (cacheEnabled) {

executor = new CachingExecutor(executor);
// adopt interceptorChain Traverse all plug-ins as executor enhance , Add the function of plug-in 
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;

Executor There are three basic implementation classes :

  • BatchExecutor: Batch actuators , Perform batch update 、 Insert, etc .
  • ReuseExecutor: Reusable actuators , Cache and reuse Statement(Statement、PreparedStatement、CallableStatement).
  • SimpleExecutor: The default actuator , Each execution creates new Statement.

All three actuators inherit from the abstract BaseExecutor, At the same time, if the L2 cache function is enabled , There will also be a decoration here CachingExecutor The ability to add L2 cache to it . Also note that there is an interceptor wrapped at the end of this code , That is, the implementation of the extension , This part is analyzed in an article .

SQL perform

The code of L2 cache is very simple , I'll skip it here , So go straight to BaseExecutor.query Method :

 public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {

// obtain sql Sentence information , Include placeholders , Parameter information 
BoundSql boundSql = ms.getBoundSql(parameter);
// Assembled cache key value 
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, 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) {
// Check current executor Whether to shut down 
throw new ExecutorException("Executor was closed.");
if (queryStack == 0 && ms.isFlushCacheRequired()) {
// Non nested queries , also FlushCache Configure to true, You need to empty the L1 cache 
List<E> list;
try {

queryStack++;// Query level plus one 
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;// Query and cache 
if (list != null) {

// For the result processing of calling the stored procedure 
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {

// Cache miss , Load data from database 
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
} finally {

if (queryStack == 0) {

for (DeferredLoad deferredLoad : deferredLoads) {
// Delayed load processing 
// issue #601
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// If at present sql The first level of cache configuration is STATEMENT, After the query, empty a set of cache 
// issue #482
return list;

First from the first level cache localCache Take it inside , without , To really access the database , And store the returned results into the first level cache .

 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);// Add a placeholder to the cache 
try {

// Call abstract method doQuery, Method to query the database and return the result , Optional implementations include :simple、reuse、batch
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {

localCache.removeObject(key);// Delete placeholders from cache 
localCache.putObject(key, list);// Add the real result object to the first level cache 
if (ms.getStatementType() == StatementType.CALLABLE) {
// If you call a stored procedure 
localOutputParameterCache.putObject(key, parameter);// Cache output type result parameters 
return list;

there doQuery It is implemented by subclasses , namely Template pattern , With SimpleExecutor For example :

 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();// obtain configuration object 
// establish StatementHandler object ,
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//StatementHandler objects creating stmt, And use parameterHandler Handle placeholders 
stmt = prepareStatement(handler, ms.getStatementLog());
// adopt statementHandler Object call ResultSetHandler Converts the result set to the specified object and returns 
return handler.<E>query(stmt, resultHandler);
} finally {


Read through the code here and we can find ,Executor Itself will not access the database , But as a commander , Command three younger brothers :

  • StatementHandler: establish PreparedStatementStatement and CallableStatement object .
  • ParameterHandler: stay StatementHandler Create... In the constructor , For precompiled SQL Statement to set parameters .
  • ResultSetHandler: stay StatementHandler Create... In the constructor , The result set returned to the database (ResultSet) encapsulate , Returns the entity type specified by the user .

The above three objects are all in configuration.newStatementHandler Method , And then call prepareStatement Get the right Statement, If it is precompiled, it will also set parameters :

 private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {

Statement stmt;
// obtain connection Object's dynamic proxy , Add logging capability ;
Connection connection = getConnection(statementLog);
// Through different StatementHandler, utilize connection establish (prepare)Statement
stmt = handler.prepare(connection, transaction.getTimeout());
// Use parameterHandler Handle placeholders 
return stmt;

If in DEBUG Got it in mode Connection The object is ConnectionLogger, This is connected with the content of the first article . After that query Method call execute perform SQL sentence , And use ResultSetHandler Processing result set :

 public List<Object> handleResultSets(Statement stmt) throws SQLException {

ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
// Used to save the result set object 
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
//statment Multiple result set objects may be returned , Here we take out the first result set 
ResultSetWrapper rsw = getFirstResultSet(stmt);
// Get the corresponding result set resultMap, The essence is to get fields and java Attribute mapping rules 
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int resultMapCount = resultMaps.size();
validateResultMapsCount(rsw, resultMapCount);// Result set and resultMap Can't be empty , Throw an exception for null 
while (rsw != null && resultMapCount > resultSetCount) {

// Get the corresponding of the current result set resultMap
ResultMap resultMap = resultMaps.get(resultSetCount);
// According to mapping rules (resultMap) Convert the result set , After converting to the target object, put it into multipleResults in 
handleResultSet(rsw, resultMap, multipleResults, null);
rsw = getNextResultSet(stmt);// Get the next result set 
cleanUpAfterHandlingResultSet();// Empty nestedResultObjects object 
// Get multiple result sets . Multiple result sets usually appear in the execution of stored procedures , The stored procedure returns multiple resultset,
//mappedStatement.resultSets Property lists the names of multiple result sets , Split with a comma ;
// The processing of multiple result sets is not the focus , Don't analyze 
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);
return collapseSingleResultList(multipleResults);

This is finally through Reflection module as well as Configuration Class result Mapping the results of related configurations :

 private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {

try {

if (parentMapping != null) {
// Handle nested mapping of multiple result sets 
handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
} else {

if (resultHandler == null) {
// If resultHandler It's empty , Instantiate a default person resultHandler
DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
// Yes ResultSet mapping , Mapping result exists temporarily resultHandler in 
handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
// Will exist for the time being resultHandler Mapping results in , Fill in multipleResults
} else {

// Use specified rusultHandler convert 
handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
} finally {

// issue #228 (close resultsets)
// call resultset.close() Close result set 
public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {

if (resultMap.hasNestedResultMaps()) {
// Handle nested resultmap The situation of 
handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
} else {
// Processing is not nested resultmap The situation of 
handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
throws SQLException {

// Create result context , The so-called context is to cache the result object in the loop 
DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
//1. According to the paging information , Navigate to the specified record 
skipRows(rsw.getResultSet(), rowBounds);
//2.shouldProcessMoreRows Determine whether you need to map subsequent results , Actually, it's still page turning , Avoid exceeding limit
while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {

//3. Further refinement resultMap Information , It mainly deals with the information of the discriminator 
ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
//4. Read resultSet A row of records in and mapped , Convert and return the target object 
Object rowValue = getRowValue(rsw, discriminatedResultMap);
//5. Save the mapping result object 
storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {

final ResultLoaderMap lazyLoader = new ResultLoaderMap();
//4.1 according to resultMap Of type attribute , Instantiate target object 
Object rowValue = createResultObject(rsw, resultMap, lazyLoader, null);
if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {

//4.2 Encapsulate the target object to get metaObjcect, Prepare for subsequent assignment operations 
final MetaObject metaObject = configuration.newMetaObject(rowValue);
boolean foundValues = this.useConstructorMappings;// Gets whether to initialize the property value using the constructor 
if (shouldApplyAutomaticMappings(resultMap, false)) {
// Whether to use automatic mapping 
//4.3 In general autoMappingBehavior The default value is PARTIAL, Automatically map fields that do not explicitly specify mapping rules 
foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
//4.4 mapping resultMap Explicitly specify the columns to be mapped in 
foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
foundValues = lazyLoader.size() > 0 || foundValues;
//4.5 If there is no attribute successfully mapped , According to <returnInstanceForEmptyRow> Configuration return for null Or the result object 
rowValue = foundValues || configuration.isReturnInstanceForEmptyRow() ? rowValue : null;
return rowValue;
  • Automatic mapping
 private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {

// obtain resultSet Existing in , however ResultMap There are no explicitly mapped columns in , Fill to autoMapping in 
List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
boolean foundValues = false;
if (!autoMapping.isEmpty()) {

// Traverse autoMapping, Copy attributes through automatic matching 
for (UnMappedColumnAutoMapping mapping : autoMapping) {

// adopt typeHandler from resultset Middle value 
final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
if (value != null) {

foundValues = true;
if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) {

// gcode issue #377, call setter on nulls (value is not 'found')
// adopt metaObject Assign a value to a property 
metaObject.setValue(mapping.property, value);
return foundValues;
  • Specified mapping
 private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
throws SQLException {

// from resultMap Get the set of column names that explicitly need to be converted 
final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
boolean foundValues = false;
// obtain ResultMapping aggregate 
final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
for (ResultMapping propertyMapping : propertyMappings) {

String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);// Get column name , Pay attention to the handling of prefixes 
if (propertyMapping.getNestedResultMapId() != null) {

// the user added a column attribute to a nested result map, ignore it
// If the attribute passes through another resultMap mapping , It ignores 
column = null;
if (propertyMapping.isCompositeResult()// If it is a nested query ,column={prop1=col1,prop2=col2}
|| (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH)))// Basic type mapping 
|| propertyMapping.getResultSet() != null) {
// Results of nested queries 
// Get attribute value 
Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
// issue #541 make property optional
// Get attribute name 
final String property = propertyMapping.getProperty();
if (property == null) {
// If the property name is empty, it will jump out of the loop 
} else if (value == DEFERED) {
// Properties, DEFERED, Processing of delayed loading 
foundValues = true;
if (value != null) {

foundValues = true;
if (value != null || (configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive())) {

// gcode issue #377, call setter on nulls (value is not 'found')
// adopt metaObject Set the property value for the target object 
metaObject.setValue(property, value);
return foundValues;

The code for reflecting instantiated objects is relatively long , But the logic is clear , The above key process codes are also annotated , Readers can refer to the source code to read .


Mybatis The core principle is analyzed , Comparison Spring The source code is much simpler , But the elegance of the code and excellent design ideas are no less than Spring, It's also worth learning . But this 3 This article only analyzes Mybaits The core implementation principle of , In addition, there are plug-ins how to extend 、 What methods will the interceptor intercept and Mybatis and Spring How to realize the integration of ? Readers can think about it , The answer will be revealed in the next article .

copyright:author[Don't talk at night],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130725548641.html