通过git下载mybatis源码,地址为github上:mybatis/mybatis-3.git
将ip拷贝到C:\Windows\System32\drivers\etc\hosts配置下,告诉计算机github的跳转ip
通过git下载源码或者以zip格式下载后再导入ieda
按照官方的使用规范,项目导入后的的目录结构如下
赋值官方的执行语句,我们在test包下简历测试连接MybatisJdbc.java类,源码项目中pom.xml已经引入了mybatis包和mysql数据库驱动
<!--mybatis包-->
<parent>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-parent</artifactId>
<version>32</version>
<relativePath />
</parent>
<artifactId>mybatis</artifactId>
<version>3.5.7-SNAPSHOT</version>
<packaging>jar</packaging>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
<scope>test</scope>
</dependency>
package org.apache.ibatis.jdbcdemo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class MybatisJdbc {
public static void main(String[] args) throws Exception {
String resource = "resources/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
System.out.println(blog);
}
}
mybatis-config.xml配置了数据库链接、映射文件、dtd约束方言
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="resources/jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="resources/mapper/BlogMapper.xml"/>
</mappers>
</configuration>
mybatis-3-config.dtd约束文件点击进去可以查看xml配置中允许配置的项,例如configuration里面还可以配置的项可以从dtd里面看到
mybatis中${}标识字符串替换,#{}是预编译符号,数据库的配置信息jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/score?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
username=root
password=root
映射中BlogMapper.xml定义了工作空间,语句id
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="org.apache.ibatis.jdbcdemo.Blog">
select * from Blog where id = #{id}
</select>
</mapper>
mybatis-3-mapper.dtd规定了mapper的约束方言
源码才是改讲的重要话题,接下来我们结合刚才的查询语句进行源码分析
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
传递文件流进行解析,通过XMLConfigBuilder把文件流解析成xml文件
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);//把文件流解析成xml文件
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的parse方法,程序加载只执行一次,通过mybatis-config.xml根节点表达式configuration获取到配置节点信息,组织为XNode节点的方式
public Configuration parse() {
if (parsed) {//此处标识只能调用一次
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration")); //parser.evalNode()方法把表达式转成XNode节点模式,获取节点configuration下的内容
return configuration;
}
//XNode节点字段
public class XNode {
private final Node node;
private final String name;
private final String body;
private final Properties attributes;
private final Properties variables;
private final XPathParser xpathParser;
}
按顺序解析configuration节点下的所有元素
/** 解析configuration节点下的所有元素
* @param root
*/
private void parseConfiguration(XNode root) {
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"));//解析xml映射文件
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
具体来分析数据库的解析过程environmentsElement(root.evalNode("environments"));因为数据库配置都放在节点environments里面,所以方法名叫environmentsElement,我们先看看xml中配置的数据库信息
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
environmentsElement方法
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));//得到事务工厂
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));//获取数据库工厂
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
break;
}
}
}
}
通过方法transactionManagerElement调用,使用反射得到TransactionFactory
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type"); //事务的类型
Properties props = context.getChildrenAsProperties();
TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();//通过反射机制得到事务工厂
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a TransactionFactory.");
}
通过方法dataSourceElement调用,使用反射机制得到DataSourceFactory
private DataSourceFactory dataSourceElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type");
Properties props = context.getChildrenAsProperties(); //获取到数据库的链接信息
DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();//使用反射机制
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a DataSourceFactory.");
}
<!--遍历数据库配置的name和value值-->
public Properties getChildrenAsProperties() {
Properties properties = new Properties();
for (XNode child : getChildren()) {
String name = child.getStringAttribute("name");
String value = child.getStringAttribute("value");
if (name != null && value != null) {
properties.setProperty(name, value);
}
}
return properties;
}
通过TransactionFactory和DataSourceFactory获取到dataSource、创建environmentBuilder,构建environment实体需要的字段值。
通过方法mapperElement解析mapper节点数据
/**
* @param 解析mapper节点数据
* @throws Exception
*/
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) { //先判断是否为package节点
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {//先判断resource方式
ErrorContext.instance().resource(resource);
try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
}
} else if (resource == null && url != null && mapperClass == null) { //判断url方式
ErrorContext.instance().resource(url);
try(InputStream inputStream = Resources.getUrlAsStream(url)){
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
}
} else if (resource == null && url == null && mapperClass != null) { //判断class方式
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
从源代码可以看出mapper的组织方式有四种,判断的顺序分别为
//先判断是否为package节点、//先判断resource方式、//判断url方式//判断class方式
<mappers>
<!-- <package name=""/>-->
<mapper resource="resources/mapper/BlogMapper.xml"/>
<mapper url=""/>
<mapper class=""/>
</mappers>
循环遍历读取mapper.xml配置文件,resource方式,传递目录名,转成文件流,在把文件流解析问xml文件,从xml文件中解析sql语句
try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());//文件流转成xml文件
mapperParser.parse(); //解析xml文件
}
XMLMapperBuilder.parse()方法解析xml文件,mapper.xml文件示例
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="org.apache.ibatis.jdbcdemo.Blog">
select * from Blog where id = #{id}
</select>
</mapper>
public void parse() {
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper")); //获取到mapper节点下的所有数据,转成XNode节点,进行解析
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
获取到mapper节点下的所有数据,转成XNode节点,进行解析
private void configurationElement(XNode context) {
try {
String namespace = context.getStringAttribute("namespace"); //获取映射文件的namespace
if (namespace == null || namespace.isEmpty()) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
resultMapElements(context.evalNodes("/mapper/resultMap"));
sqlElement(context.evalNodes("/mapper/sql"));
buildStatementFromContext(context.evalNodes("select|insert|update|delete")); //解析增删改查方法
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
}
}
解析增删改查的方法,最后会构建一个MappedStatement实体,用于存放解析到的内容
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
执行完语句SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);数据库连接信息和执行语句已经解析完,做好相关操作的准备了
开始来分析打开session代码,configuration.getDefaultExecutorType()为之前解析时设置的执行器类型,
SqlSession sqlSession = sqlSessionFactory.openSession();
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
执行器有三种类型
public enum ExecutorType {
SIMPLE, REUSE, BATCH
}
在执行创建sqlsession方法openSessionFromDataSource中,从之前读取完mybatis.xml配置后设置到environment实体中获取配置信息,根据environment获取TransactionFactory,通过environment创建Transaction,创建一个执行器,默认是SIMPLE,创建模式sqlsessiion
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); //创建一个执行器,默认是SIMPLE
return new DefaultSqlSession(configuration, executor, autoCommit); //创建模式sqlsessiion
} 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();
}
}
三种执行器创建代码,从代码 executor = new CachingExecutor(executor);可以看出一级缓存默认开启
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 (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
执行器的关系:
SimpleExecutor、BatchExecutor、ReuseExecutor都extends BaseExecutor ;public abstract class BaseExecutor implements Executor
执行完SqlSession sqlSession = sqlSessionFactory.openSession();做的事为创建执行器,开启一级缓存
接下来分析Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
@Override
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);//通过参数和执行语句id查询数据
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {//查询记录为一条,查询出来结果大于1则抛出异常
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
通过执行语句组合id从之前解析存放在configuration中取出实体MappedStatement
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement); //通过执行语句id从之前解析存放在configuration中取值,获取到执行sql
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
从实体MappedStatement中取出执sql,封装成BoundSql实体
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);//获取到执行的sql及参数组织的实体类
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
根据boundSql实体组织CacheKey缓存数据
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
CacheKey cacheKey = new CacheKey();//创建一级缓存
cacheKey.update(ms.getId());
cacheKey.update(rowBounds.getOffset());
cacheKey.update(rowBounds.getLimit());
cacheKey.update(boundSql.getSql());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
// mimic DefaultParameterHandler logic
for (ParameterMapping parameterMapping : parameterMappings) {
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);
}
cacheKey.update(value);
}
}
if (configuration.getEnvironment() != null) {
// issue #176
cacheKey.update(configuration.getEnvironment().getId());
}
//组织一级缓存-49199703:2163988625:org.mybatis.example.BlogMapper.selectBlog:0:2147483647:select * from Blog where id = ?:101:development
return cacheKey;
}
通过执行sql实体和缓存数据查询数据,若是二级缓存不为空则从二级缓存中取数据
@Override
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);//执行后台数据查询
tcm.putObject(cache, key, list); // 把查询结果赋值给二级缓存中
}
return list;
}
}
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
二级缓存为空,则从一级缓存或者查询后台数据
@Override
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++;
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;
}
查询数据库的方法doQuery
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;//java.sql;操作数据库的链接
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);
}
}
使用stmt = prepareStatement(handler, ms.getStatementLog()); 得到数据库链接
/**
* 得到数据库的链接
* @throws SQLException
*/
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
最终由Statement 到PreparedStatement,执行execute(),执行数据库的jdbc操作
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
return resultSetHandler.handleResultSets(ps);
}
一级缓存只能用做同一个sqlsession中有效,开启二级缓存,在xml文件中进行配置,二级缓存可以跨过sqlsession从缓存中取值
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>