面试官:你分析过mybatis工作原理吗?

MyBatis 工作原理基于 Spring + SpringMVC + MyBatis 整合项目,分为六个部分:

  1. 读取核心配置文件并返回 InputStream 流对象。
  2. 根据 InputStream 流对象解析出 Configuration 对象,然后创建 SqlSessionFactory 工厂对象。
  3. 根据一系列属性从 SqlSessionFactory 工厂中创建 SqlSession。
  4. 从 SqlSession 中调用 Executor 执行数据库操作并生成具体 SQL 指令。
  5. 对执行结果进行二次封装。
  6. 提交与事务。

实体类:
public class Book {
private long bookId;// 图书ID
private String name;// 图书名称
private int number;// 馆藏数量
getter and setter ...
}

  1. 读取核心配置文件
    1.1 配置文件 mybatis-config.xml

XML 中还可以配置很多内容,上面示例是最关键的部分。要注意 XML 头部的声明,用来验证 XML 文档的正确性。environment 元素体中包含事务管理和连接池的配置。mappers 元素包含一组 mapper 映射器,这些 mapper 的 XML 文件包含 SQL 代码和映射定义信息。

1.2 BookMapper.xml

insert into book (name,number) values (#{name},#{number})

1.3 Main 方法
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置,也可以使用任意输入流 InputStream 实例,包括字符串形式的文件路径或者 file:// URL 形式的文件路径。MyBatis 包含 Resources 工具类,可使从 classpath 或其他位置加载资源文件更加容易。

public class Main {
public static void main(String[] args) throws IOException {
// 创建一个book对象
Book book = new Book();
book.setBookId(1006);
book.setName("Easy Coding");
book.setNumber(110);
// 加载配置文件 并构建SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 从SqlSessionFactory对象中获取 SqlSession对象
SqlSession sqlSession = factory.openSession();
// 执行操作
sqlSession.insert("insert", book);
// 提交操作
sqlSession.commit();
// 关闭SqlSession
sqlSession.close();
}
}

下面从该示例的入口开始分析。

  1. 根据配置文件生成 SqlSessionFactory 工厂对象
    2.1 Resources.getResourceAsStream(resource)
    Resources 是 MyBatis 提供的加载资源文件的工具类。getResourceAsStream 方法如下:
    public static InputStream getResourceAsStream(String resource) throws IOException {
    return getResourceAsStream((ClassLoader)null, resource);
    }

它继续调用以下方法:
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
if (in == null) {
throw new IOException("Could not find resource " + resource);
} else {
return in;
}
}

获取 ClassLoader 对象后,交给 ClassLoader 加载资源:
InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
for (ClassLoader cl : classLoader) {
if (null != cl) {
InputStream returnValue = cl.getResourceAsStream(resource);
if (null == returnValue) {
returnValue = cl.getResourceAsStream("/" + resource);
}
if (null != returnValue) {
return returnValue;
}
}
}
return null;
}

该方法最终返回一个 InputStream 对象。

2.2 new SqlSessionFactoryBuilder().build(inputStream)
public SqlSessionFactoryBuilder() {
}

new SqlSessionFactoryBuilder() 只是创建对象实例,使用了建造者模式,对象的返回交给 build() 方法。
public SqlSessionFactory build(InputStream inputStream) {
return this.build((InputStream)inputStream, (String)null, (Properties)null);
}

这里传入上一步获取到的 InputStream 对象。
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
SqlSessionFactory var5;
try {
// 进行XML配置文件的解析
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
var5 = this.build(parser.parse());
} catch (Exception var14) {
throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException var13) {
}
}
return var5;
}

解析时通过 Document 对象解析 XML,然后交给 XMLConfigBuilder 构造成 org.apache.ibatis.session.Configuration 对象,再交给 build() 方法构造 SqlSessionFactory:
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}

public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}

  1. 创建 SqlSession
    SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法,可以通过 SqlSession 实例直接执行已映射的 SQL 语句。
    public SqlSession openSession() {
    return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);
    }

调用自身的 openSessionFromDataSource 方法:

  1. getDefaultExecutorType() 默认是 SIMPLE。
  2. 事务隔离等级是 null,autoCommit 是 false。

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
DefaultSqlSession var8;
try {
Environment environment = this.configuration.getEnvironment();
// 根据Configuration的Environment属性来创建事务工厂
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
// 从事务工厂中创建事务,默认等级为null,autoCommit=false
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 创建执行器
Executor executor = this.configuration.newExecutor(tx, execType);
// 根据执行器创建返回对象 SqlSession
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
} catch (Exception var12) {
this.closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);
} finally {
ErrorContext.instance().reset();
}
return var8;
}

构建步骤:Environment -> TransactionFactory + autoCommit + tx-level -> Transaction + ExecType -> Executor + Configuration + autoCommit -> SqlSession。其中 Environment 是 Configuration 中的属性。

  1. 调用 Executor 执行数据库操作并生成具体 SQL 指令
    拿到 SqlSession 对象后,调用 insert 方法:
    public int insert(String statement, Object parameter) {
    return this.update(statement, parameter);
    }

它调用自身的 update(statement, parameter) 方法:
public int update(String statement, Object parameter) {
int var4;
try {
this.dirty = true;
MappedStatement ms = this.configuration.getMappedStatement(statement);
// wrapCollection(parameter)判断param对象是否是集合
var4 = this.executor.update(ms, this.wrapCollection(parameter));
} catch (Exception var8) {
throw ExceptionFactory.wrapException("Error updating database. Cause: " + var8, var8);
} finally {
ErrorContext.instance().reset();
}
return var4;
}

mappedStatements 就是平时说的 SQL 映射对象,源码如下:
protected final Map<String, MappedStatement> mappedStatements;

它是一个 Map 集合。加载 XML 配置时,mapper.xml 的 namespace 和 id 信息会存放为 mappedStatements 的 key,对应的 SQL 语句就是 value。

然后调用 BaseExecutor 中的 update 方法:
public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if (this.closed) {
throw new ExecutorException("Executor was closed.");
} else {
this.clearLocalCache();
// 真正做执行操作的方法
return this.doUpdate(ms, parameter);
}
}

doUpdate 才是真正执行操作的方法:
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
int var6;
try {
Configuration configuration = ms.getConfiguration();
// 创建StatementHandler对象,从而创建Statement对象
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, (ResultHandler)null, (BoundSql)null);
// 将sql语句和参数绑定并生成SQL指令
stmt = this.prepareStatement(handler, ms.getStatementLog());
var6 = handler.update(stmt);
} finally {
this.closeStatement(stmt);
}
return var6;
}

prepareStatement 方法展示了 MyBatis 如何拼接 SQL:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Connection connection = this.getConnection(statementLog);
// 准备Statement
Statement stmt = handler.prepare(connection);
// 设置SQL查询中的参数值
handler.parameterize(stmt);
return stmt;
}

parameterize 方法如下:
public void parameterize(Statement statement) throws SQLException {
this.parameterHandler.setParameters((PreparedStatement)statement);
}

这里把 statement 转换为 PreparedStatement 对象,它比 Statement 更快、更安全。这些都是 JDBC 中常用的对象,也可以看出 MyBatis 是对 JDBC 的封装。

从 ParameterMapping 中读取参数值和类型,然后设置到 SQL 语句中:
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(this.mappedStatement.getParameterMap().getId());
List parameterMappings = this.boundSql.getParameterMappings();
if (parameterMappings != null) {
for(int i = 0; i < parameterMappings.size(); ++i) {
ParameterMapping parameterMapping = (ParameterMapping)parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
String propertyName = parameterMapping.getProperty();
Object value;
if (this.boundSql.hasAdditionalParameter(propertyName)) {
value = this.boundSql.getAdditionalParameter(propertyName);
} else if (this.parameterObject == null) {
value = null;
} else if (this.typeHandlerRegistry.hasTypeHandler(this.parameterObject.getClass())) {
value = this.parameterObject;
} else {
MetaObject metaObject = this.configuration.newMetaObject(this.parameterObject);
value = metaObject.getValue(propertyName);
}

            TypeHandler typeHandler = parameterMapping.getTypeHandler();
            JdbcType jdbcType = parameterMapping.getJdbcType();
            if (value == null && jdbcType == null) {
                jdbcType = this.configuration.getJdbcTypeForNull();
            }

            try {
                typeHandler.setParameter(ps, i + 1, value, jdbcType);
            } catch (TypeException var10) {
                throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + var10, var10);
            } catch (SQLException var11) {
                throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + var11, var11);
            }
        }
    }
}

}

  1. 对查询结果二次封装
    在 doUpdate 方法中解析生成完 SQL 后,执行 handler.update(stmt),源码如下:
    public int update(Statement statement) throws SQLException {
    PreparedStatement ps = (PreparedStatement)statement;
    // 执行sql
    ps.execute();
    // 获取返回值
    int rows = ps.getUpdateCount();
    Object parameterObject = this.boundSql.getParameterObject();
    KeyGenerator keyGenerator = this.mappedStatement.getKeyGenerator();
    keyGenerator.processAfter(this.executor, this.mappedStatement, ps, parameterObject);
    return rows;
    }

因为示例是插入操作,返回 int 类型的值,所以 MyBatis 直接返回 int。如果是 query 操作,返回的是 ResultSet,MyBatis 会将查询结果包装成 ResultSetWrapper 类型,然后一步步对应 Java 类型赋值。

  1. 提交与事务
    最后看 commit() 方法的源码:
    public void commit() {
    this.commit(false);
    }

调用对象本身的 commit(boolean force) 方法:
public void commit(boolean force) {
try {
// 是否提交(判断是提交还是回滚)
this.executor.commit(this.isCommitOrRollbackRequired(force));
this.dirty = false;
} catch (Exception var6) {
throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + var6, var6);
} finally {
ErrorContext.instance().reset();
}
}

如果 dirty 是 false,则进行回滚;如果是 true,则正常提交。
private boolean isCommitOrRollbackRequired(boolean force) {
return !this.autoCommit && this.dirty || force;
}

调用 CachingExecutor 的 commit 方法:
public void commit(boolean required) throws SQLException {
this.delegate.commit(required);
this.tcm.commit();
}

调用 BaseExecutor 的 commit 方法:
public void commit(boolean required) throws SQLException {
if (this.closed) {
throw new ExecutorException("Cannot commit, transaction is already closed");
} else {
this.clearLocalCache();
this.flushStatements();
if (required) {
this.transaction.commit();
}
}
}

最后调用 JDBCTransaction 的 commit 方法:
public void commit() throws SQLException {
if (this.connection != null && !this.connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Committing JDBC Connection [" + this.connection + "]");
}
// 提交连接
this.connection.commit();
}
}

参考来源:https://zhuanlan.zhihu.com/p/59792101