建行二面:Mybatis 是如何工作的?
MyBatis 是一款優(yōu)秀的持久層框架,它通過(guò)簡(jiǎn)化 JDBC操作和提供靈活的 SQL映射方式,使 Java 開(kāi)發(fā)人員能夠更高效地進(jìn)行數(shù)據(jù)庫(kù)操作。那么,MyBatis的執(zhí)行原理是什么?這篇文章我們將深入地分析。
一、MyBatis 配置解析
MyBatis 的配置文件通常包括全局配置文件(mybatis-config.xml)和映射文件(XXXMapper.xml)。全局配置文件主要用于配置數(shù)據(jù)源和其他全局性的信息,而映射文件則用于定義 SQL 語(yǔ)句。
1. 全局配置文件解析
全局配置文件在 MyBatis 啟動(dòng)時(shí)被解析。SqlSessionFactoryBuilder 是 MyBatis 解析配置文件的入口點(diǎn)。它通過(guò) build 方法接收一個(gè) Reader 或 InputStream,然后調(diào)用 XMLConfigBuilder 來(lái)解析 XML 配置文件。
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} 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.
}
}
}
XMLConfigBuilder 解析配置文件并構(gòu)建出 Configuration 對(duì)象,該對(duì)象包含了 MyBatis 的所有配置信息。
2. 映射文件解析
映射文件中定義了 SQL 語(yǔ)句,通過(guò) XMLMapperBuilder 進(jìn)行解析。每個(gè) <mapper> 標(biāo)簽對(duì)應(yīng)一個(gè) MappedStatement 對(duì)象,MappedStatement 包含了 SQL 語(yǔ)句、輸入輸出參數(shù)類(lèi)型、結(jié)果集映射等信息。
public void parse() {
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
二、SQL 語(yǔ)句解析
MyBatis 支持動(dòng)態(tài) SQL,通過(guò) <if>, <choose>, <foreach> 等標(biāo)簽,可以根據(jù)不同的條件構(gòu)造 SQL。動(dòng)態(tài) SQL 是 MyBatis 的一大特色,通過(guò) SqlSource 接口實(shí)現(xiàn)。SqlSource 的主要實(shí)現(xiàn)類(lèi)有 StaticSqlSource, DynamicSqlSource, RawSqlSource 等。
動(dòng)態(tài) SQL 解析
DynamicSqlSource 是處理動(dòng)態(tài) SQL 的核心類(lèi)。它通過(guò) SqlNode 樹(shù)來(lái)表示 SQL 語(yǔ)句的結(jié)構(gòu),SqlNode 是一個(gè)接口,常用的實(shí)現(xiàn)類(lèi)有 IfSqlNode, ChooseSqlNode, WhereSqlNode 等。每個(gè) SqlNode 的 apply 方法負(fù)責(zé)將節(jié)點(diǎn)轉(zhuǎn)換為 SQL 字符串。
public class DynamicSqlSource implements SqlSource {
private final Configuration configuration;
private final SqlNode rootSqlNode;
public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) {
this.configuration = configuration;
this.rootSqlNode = rootSqlNode;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
DynamicContext context = new DynamicContext(configuration, parameterObject);
rootSqlNode.apply(context);
SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
return sqlSource.getBoundSql(parameterObject);
}
}
三、參數(shù)設(shè)置
在獲得最終的 SQL 語(yǔ)句后,MyBatis 需要將參數(shù)傳遞給 SQL 語(yǔ)句。ParameterHandler 接口負(fù)責(zé)這項(xiàng)工作,默認(rèn)實(shí)現(xiàn)是 DefaultParameterHandler。
public class DefaultParameterHandler implements ParameterHandler {
private final TypeHandlerRegistry typeHandlerRegistry;
private final MappedStatement mappedStatement;
private final Object parameterObject;
private final BoundSql boundSql;
private final Configuration configuration;
public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
this.mappedStatement = mappedStatement;
this.configuration = mappedStatement.getConfiguration();
this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
this.parameterObject = parameterObject;
this.boundSql = boundSql;
}
@Override
public void setParameters(PreparedStatement ps) throws SQLException {
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)) {
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();
}
typeHandler.setParameter(ps, i + 1, value, jdbcType);
}
}
}
}
}
四、SQL 執(zhí)行
SQL 執(zhí)行是 MyBatis 的核心功能之一。Executor 接口定義了執(zhí)行操作的基本方法,主要的實(shí)現(xiàn)類(lèi)有 SimpleExecutor, ReuseExecutor, BatchExecutor。這些執(zhí)行器通過(guò) StatementHandler 執(zhí)行 SQL 語(yǔ)句。
public class SimpleExecutor extends BaseExecutor {
public SimpleExecutor(Configuration configuration, Transaction transaction) {
super(configuration, transaction);
}
@Override
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.update(stmt);
} finally {
closeStatement(stmt);
}
}
}
五、結(jié)果處理
MyBatis 提供了強(qiáng)大的結(jié)果集映射功能,允許將 SQL 查詢結(jié)果映射為 Java 對(duì)象。ResultSetHandler 接口負(fù)責(zé)處理結(jié)果集,DefaultResultSetHandler 是其主要實(shí)現(xiàn)類(lèi)。
public class DefaultResultSetHandler implements ResultSetHandler {
private final TypeHandlerRegistry typeHandlerRegistry;
private final ObjectFactory objectFactory;
private final boolean useConstructorMappings;
private final ReflectorFactory reflectorFactory;
private final MappedStatement mappedStatement;
private final RowBounds rowBounds;
private final ParameterHandler parameterHandler;
private final ResultHandler<?> resultHandler;
private final BoundSql boundSql;
public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultHandler<?> resultHandler, BoundSql boundSql, RowBounds rowBounds) {
this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
this.objectFactory = mappedStatement.getConfiguration().getObjectFactory();
this.useConstructorMappings = mappedStatement.getConfiguration().isUseConstructorMappings();
this.reflectorFactory = mappedStatement.getConfiguration().getReflectorFactory();
this.mappedStatement = mappedStatement;
this.rowBounds = rowBounds;
this.parameterHandler = parameterHandler;
this.resultHandler = resultHandler;
this.boundSql = boundSql;
}
@Override
public List<Object> handleResultSets(Statement stmt) throws SQLException {
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
ResultSetWrapper rsw = getFirstResultSet(stmt);
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
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++;
}
return collapseSingleResultList(multipleResults);
}
}
六、總結(jié)
本文,我們通過(guò)核心源碼分析了 MyBatis, 它是一個(gè)輕量級(jí)的 ORM框架,它通過(guò)配置文件和注解將 Java 對(duì)象與數(shù)據(jù)庫(kù)記錄映射起來(lái),其核心在于通過(guò) XML和注解配置 SQL語(yǔ)句,利用執(zhí)行器執(zhí)行 SQL,并通過(guò)結(jié)果集處理器將結(jié)果映射為 Java對(duì)象。
MyBatis的設(shè)計(jì)使得開(kāi)發(fā)者可以專(zhuān)注于 SQL本身,而不必關(guān)心底層 JDBC操作的細(xì)節(jié),了解和掌握其執(zhí)行原理和設(shè)計(jì)模式,可以幫組我們?cè)趯?shí)際應(yīng)用中更好地使用 MyBatis。