mybatis之builder包处理mybatis初始化
mybatis有两种xml的文件,一种是Mybatis-config.xml负责配置mybatis的各种配置以及指定映射文件;一种是xml映射文件负责sql。
其中配置文件有很多子节点,各自有各自的功能,xml也有多种子节点resultMap、sql、select、insert、update要解析这些复杂的配置为对象,一个简单的类肯定是不够的,
这个时候就需要各个不通职责的子类合作来解析配置和映射文件。mybatis通过建造者模式来解析配置文件和映射文件。
建造者模式: 是将一个复杂的对象的构建与它的标识分离。使得同样的构建过程可以创建不同的表示。建造者隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的>方式,动态的创建具有符合属性的对象。
调用关系
读取myabits-config.xml的配置,解析各个子节点,以及配置的映射文件,解析映射文件中的各个子节点。
SqlSessionFactoryBuilder.build() : 读取mybatis配置文件
XMLConfigBuilder.parse() : 解析配置文件
XMLMapperBuilder.parse() : 解析映射文件
XMLStatementBuilder.parseStatementNode() : 解析映射文件中select|insert|update|delete子节点
RawLanguageDriver.createSqlSource() : 开始解析节点中的sql语句
XMLLanguageDriver.createSqlSource() :
XMLScriptBuilder.parseScriptNode() : 负责解析sql中的动态语句
RawSqlSource.RawSqlSource() :构造方法
SqlSourceBuilder.parse() :
BaseBuilder
解析配置文件和映射文件的基础类,存储了configuration、配置类型别名、类型处理器、及通过string查询JDBC枚举类型,为子类提供公共服务。
public abstract class BaseBuilder {
// mybatis配置文件解析的对象
protected final Configuration configuration;
// 类型别名,减少代码中的冗余
protected final TypeAliasRegistry typeAliasRegistry;
// 类型处理器
protected final TypeHandlerRegistry typeHandlerRegistry;
public BaseBuilder(Configuration configuration) {
this.configuration = configuration;
this.typeAliasRegistry = this.configuration.getTypeAliasRegistry();
this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();
}
public Configuration getConfiguration() {
return configuration;
}
// 类型转换 子类XMLConfigBuilder转换从mybatis-config.xml读取到的配置值
protected Pattern parseExpression(String regex, String defaultValue) {
return Pattern.compile(regex == null ? defaultValue : regex);
}
protected Boolean booleanValueOf(String value, Boolean defaultValue) {
return value == null ? defaultValue : Boolean.valueOf(value);
}
protected Integer integerValueOf(String value, Integer defaultValue) {
return value == null ? defaultValue : Integer.valueOf(value);
}
protected Set<String> stringSetValueOf(String value, String defaultValue) {
value = (value == null ? defaultValue : value);
return new HashSet<String>(Arrays.asList(value.split(",")));
}
// 根据字符串查询JdbcType枚举
protected JdbcType resolveJdbcType(String alias) {
if (alias == null) {
return null;
}
try {
return JdbcType.valueOf(alias);
} catch (IllegalArgumentException e) {
throw new BuilderException("Error resolving JdbcType. Cause: " + e, e);
}
}
// 根据类型别名查询对应的对象
protected Class<?> resolveAlias(String alias) {
return typeAliasRegistry.resolveAlias(alias);
}
// 查询类型处理器
protected TypeHandler<?> resolveTypeHandler(Class<?> javaType, Class<? extends TypeHandler<?>> typeHandlerType) {
if (typeHandlerType == null) {
return null;
}
// javaType ignored for injected handlers see issue #746 for full detail
TypeHandler<?> handler = typeHandlerRegistry.getMappingTypeHandler(typeHandlerType);
if (handler == null) {
// not in registry, create a new one
handler = typeHandlerRegistry.getInstance(javaType, typeHandlerType);
}
return handler;
}
}
XMLConfigBuilder
XMLConfigBuilder解析mybatis-config.xml核心类。解析出mybatis的配置项、加载插件、加载映射文件调用XMLMapperBuilder进行解析。
public class XMLConfiguration extends BaseBuilder {
// mybatis加载解析mybatis-config.xml全局只一次
private boolean parsed;
// xml文档语法解析器
private final XPathParser parser;
// 当前设置的环境,每一个environment对应一套环境
private String environment;
private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();
// 核心方法
public Configuration parse() {
//只解析一次
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
// 解析mybatis-config.xml中各个子节点
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(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"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
//剩余方法都是实现如何解析子节点的值,之前已经在《mybatis之Configuration解析》中有分析过
}
XMLMapperBuilder
XMLMapperBuilder发解析映射文件,主要包含: resultMap、parameterMap、sql、select、insert、update、delete、cache-ref、cache、namespace这些子节点
其中select、insert、update、delete语句的解析是由XMLStatementBuilder来处理的。cache表示这个namespace开启二级缓存,cache-ref开启二级缓存,多个空间中共享相同的缓存配置和实例。
public class XMLMapperBuilder extends BaseBuilder {
// xml文档解析器
private final XPathParser parser;
// 辅助工具类
private final MapperBuilderAssistant builderAssistant;
//存储 sql节点的共用sql语句
private final Map<String, XNode> sqlFragments;
// 映射文件资源
private final String resource;
//解析映射文件的入口方法
public void parse() {
// 每个resource全局只加载解析一次
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
// 解析映射文件中的子节点
private void configurationElement(XNode context) {
try {
// 注意这里,映射文件的namespace为必填
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
builderAssistant.setCurrentNamespace(namespace);
// 二级缓存(我们后面会专门写一篇关于mybatis缓存的)
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
// 已弃用,不做分析
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析结果映射集
resultMapElements(context.evalNodes("/mapper/resultMap"));
// 公共sql
sqlElement(context.evalNodes("/mapper/sql"));
// 解析 select、insert、update、delete
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
}
}
// 解析select|insert|update|delete节点的动态sql
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
for (XNode context : list) {
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}
// 映射文件关联的interface存储在mybatis的configuration中
private void bindMapperForNamespace() {
String namespace = builderAssistant.getCurrentNamespace();
if (namespace != null) {
Class<?> boundType = null;
try {
boundType = Resources.classForName(namespace);
} catch (ClassNotFoundException e) {
//ignore, bound type is not required
}
if (boundType != null) {
if (!configuration.hasMapper(boundType)) {
// Spring may not know the real resource name so we set a flag
// to prevent loading again this resource from the mapper interface
// look at MapperAnnotationBuilder#loadXmlResource
configuration.addLoadedResource("namespace:" + namespace);
configuration.addMapper(boundType);
}
}
}
}
}
XMLStatementBuilder
XMLStatementBuilder解析出select、update、insert、delete的语句及其节点的属性,通过MapperBuilderAssistant辅助类,构造出MappedStatement。
public class XMLStatementBuilder extends BaseBuilder {
// 辅助工具类
private final MapperBuilderAssistant builderAssistant;
// 当前要解析的select、update、insert、delete节点
private final XNode context;
// 环境对应的databaseId(数据库厂商标识)
private final String requiredDatabaseId;
// 核心方法,解析select、update、insert、delete节点的sql
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
// sql语句包含的 <include>处理
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)
// 解析出sql
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);
// update insert主键处理
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
//使用工具类构建出mybatish核心数据结构: MappedStatement
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
}
MapperBuilderAssistant
解析mybatis-config.xml及映射文件用到的辅助工具类
public class MapperBuilderAssistant extends BaseBuilder {
//当前的命名空间
private String currentNamespace;
//设置当前的命名空间,命名空间不能为空
public void setCurrentNamespace(String currentNamespace) {
if (currentNamespace == null) {
throw new BuilderException("The mapper element requires a namespace attribute to be specified.");
}
if (this.currentNamespace != null && !this.currentNamespace.equals(currentNamespace)) {
throw new BuilderException("Wrong namespace. Expected '"
+ this.currentNamespace + "' but found '" + currentNamespace + "'.");
}
this.currentNamespace = currentNamespace;
}
// 构造的MappedStatement 存放到configuration
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;
}
}
总结
1.mybatis有两种xml的文件,一种是Mybatis-config.xml负责配置mybatis的各种配置以及指定映射文件;一种是xml映射文件负责sql。
2.mybatis通过org.apache.ibatis.builder的包下的类使用建造者模式来解析配置文件和映射文件。
3.XMLMapperBuilder : 解析映射文件
4.XMLStatementBuilder : 析sql语句
5.XMLConfigBuilder : 解析mybatis配置文件
6.SqlSourceBuilder : 解析sql语句
7.MapperBuilderAssistant : 解析过程中的一些辅助类
8.baseBuilder解析配置文件和映射文件的基础类,存储了configuration、配置类型别名、类型处理器、及通过string查询JDBC枚举类型,为子类提供公共服务。
9.XMLConfigBuilder解析mybatis-config.xml核心类。解析出mybatis的配置项、加载插件、加载映射文件调用XMLMapperBuilder进行解析。
10.mybatis加载解析mybatis-config.xml全局只一次
11.XMLMapperBuilder发解析映射文件,主要包含: resultMap、parameterMap、sql、select、insert、update、delete、cache-ref、cache、namespace这些子节点
12.映射文件中配置了cache表示这个namespace开启二级缓存,cache-ref开启二级缓存,多个空间中共享相同的缓存配置和实例
13.XMLStatementBuilder解析出select、update、insert、delete的语句及其节点的属性,通过MapperBuilderAssistant辅助类,构造出MappedStatement。