mybatis例子:
配置mybatis核心配置文件
<?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>
<!-- 配置环境,制定数据库连接信息 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/activitydatas?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="liqiang" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="menuMapper.xml"/>
</mappers>
</configuration>menuMapper.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="com.liqiang.mapper.MenuMapper" >
<select id="findById" resultType="com.liqiang.test.Menu" parameterType="int" >
select * from menu where id=#{id}
</select>
</mapper>运行程序
public static void main(String[] args) {
InputStream mybatisConfig=TestMain.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(mybatisConfig);
SqlSession sqlSession= sqlSessionFactory.openSession();
List<Menu> menus =sqlSession.selectList("com.liqiang.mapper.MenuMapper.findById",67);
for (Menu menu : menus) {
System.out.println(menu.getId());
}
}运行结果

现在我们以sqlSessionFactoryBuilder为入口看看内部到底做了些什么

我们可以看到build方法提供多种重载 比如通过程序初始化数据库链接信息 或者properties
这里将mybatis的核心配置文件初始化XmlConfigBuilder 对象 然后调用他的parse方法

我们可以看出XMLConfigBuilder对象的parse方法在开始解析我们刚才配置的核心配置文件。。这些标签都是configuration下面的子标签 我们只配了mappers enviroments
我们随便进2个方法看你 内部做了些什么


可以看到 将解析后的信息都是封装在了configuration对象里面
我们重点看一下MapperElement方法做了什么

这里在循环mappers下面的mapper标签 然后载入到输入流 交给XmlMapperBuilder处理 如:
<mappers>
<mapper resource="menuMapper.xml"/>
</mappers>我们进入XmlMapperBuilder方法的parse方法看看做了什么

我们可以看到 在开始解析mappe.xml下面的节点。我们刚才配置了 select节点 我们进入 buildStateMentFromContext 看看框架获得mapper下面的select节点后做了什么

我们看到 会遍历节点通过XmlStatementBuilder的parseStatementNode进行处理
public void parseStatementNode() {
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String resultMap = context.getStringAttribute("resultMap");
String resultType = context.getStringAttribute("resultType");
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
Class<?> resultTypeClass = resolveClass(resultType);
String resultSetType = context.getStringAttribute("resultSetType");
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
String resultSets = context.getStringAttribute("resultSets");
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}红色字符是不是很熟悉。。这些就是我们mapper配置的select update delete等标签的相关属性。。将他们解析出来 然后传入
<span>builderAssistant.addMappedStatement<br />
public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
boolean resultOrdered,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) {
if (unresolvedCacheRef) {
throw new IncompleteElementException("Cache-ref not yet resolved");
}
id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
.resource(resource)
.fetchSize(fetchSize)
.timeout(timeout)
.statementType(statementType)
.keyGenerator(keyGenerator)
.keyProperty(keyProperty)
.keyColumn(keyColumn)
.databaseId(databaseId)
.lang(lang)
.resultOrdered(resultOrdered)
.resultSets(resultSets)
.resultMaps(getStatementResultMaps(resultMap, resultType, id))
.resultSetType(resultSetType)
.flushCacheRequired(valueOrDefault(flushCache, !isSelect))
.useCache(valueOrDefault(useCache, isSelect))
.cache(currentCache);
ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
if (statementParameterMap != null) {
statementBuilder.parameterMap(statementParameterMap);
}
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
return statement;
}
最终将我们mapper下面的标签封装成MappedStateMent 以map结构保存到configuration key为namespace+标签id

现在我们就大概知道 这段代码是找到对应的mapperStateMent 里面封装了参数 参数类型 返回类型 sql语句等 mybatis根据这些信息就可以操作jdbc封装返回结果了
<span> 继续往下看


我们可以得出结论
sqlSessionFactoryBuilder.build(mybatisConfig) 内部是通过XmlConfigBuilder解析mybatisy的核心配置文件 封装到configuration 然后通过configuration初始化defaultSqlSessionFactory对象
现在我们进入selectOne看看内部做了什么

前面我们分析了 mapper里面的select 等标签信息是以mappedStatement保存在configuration对象里面的map里面 key为mapper标签的namespace +标签id mappedStatement里面封装了sql parameterType resultType 等信息
我们可以看到获得mappedStatement是交给Executory的query方法执行

将mapperStatement sql语句和参数封装到boundSql 如select * from menu where id=#{id} 变成?
算出缓存key

没有缓存 执行查询



我们可以发现 statementHandle是负责构建jdbcStatement 这里的几个statement封装了jdbc的操作
我们可以看到configuration下面这些方法

这个是mybatis插件开发会用到。
StatementHandle 内部还是通过parmeterHandle来设置参数 通过resultHandel来封装结果
RoutingStatementHandel的 父类构造函数会初始化他们

- Configuration MyBatis所有的配置信息都维持在Configuration对象之中。
- SqlSession 作为MyBatis工作的主要顶层API,表示和数据库交互的会话,完成必要数据库增删改查功能
- Executor MyBatis执行器,是MyBatis 调度的核心,负责SQL语句的生成和查询缓存的维护
- StatementHandler 封装了JDBC Statement操作,负责对JDBC statement 的操作,如设置参数、将Statement结果集转换成List集合。
- ParameterHandler 负责对用户传递的参数转换成JDBC Statement 所需要的参数,
- ResultSetHandler 负责将JDBC返回的ResultSet结果集对象转换成List类型的集合;
- TypeHandler 负责java数据类型和jdbc数据类型之间的映射和转换
- MappedStatement MappedStatement维护了一条<select|update|delete|insert>节点的封装,
- SqlSource 负责根据用户传递的parameterObject,动态地生成SQL语句,将信息封装到BoundSql对象中,并返回
- BoundSql 表示动态生成的SQL语句以及相应的参数信息