spring boot 目前是比较火热的项目,比起spring mvc 去除了各种繁琐的xml配置,从而结束xml的配置时代。
今天我们就来讲讲spring boot 加载mybatis的xml的一个过程:
mybatis也是牛,为了和spring整合特地写了一个jar
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
这里面主要是mybatis利用spring的一些扩展点将mybatis和spring整合起来,废话不多说开始撸源码。
借助官方文档:
需要注意的是 SqlSessionFactoryBean 实现了 Spring 的 FactoryBean 接口
(参见 Spring 官方文档 3.8 节 通过工厂 bean 自定义实例化逻辑)。
这意味着由 Spring 最终创建的 bean 并不是 SqlSessionFactoryBean 本身,
而是工厂类(SqlSessionFactoryBean)的 getObject() 方法的返回结果。
这种情况下,Spring 将会在应用启动时为你创建 SqlSessionFactory,
并使用 sqlSessionFactory 这个名字存储起来。
等效的 Java 代码如下:
@Bean
public SqlSessionFactory sqlSessionFactory() {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
SqlSessionFactoryBean 稍微拿出来看下:
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
//用于存放mybatis-configuration.xml
private Resource configLocation;
// 各种配置,xml集中营
private Configuration configuration;
//mapper.xml文件
private Resource[] mapperLocations;
//数据源
private DataSource dataSource;
//事务工厂
private TransactionFactory transactionFactory;
//解析配置的属性
private Properties configurationProperties;
//这个是mybatis中解析开始的地方
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
//EnvironmentAware requires spring 3.1
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
//issue #19. No default provider.
private DatabaseIdProvider databaseIdProvider;
private Class<? extends VFS> vfs;
private Cache cache;
private ObjectFactory objectFactory;
private ObjectWrapperFactory objectWrapperFactory;
}
好了springboot 和mybatis的关联也就从 factoryBean.getObject()开始了
1 进入源码你会发现:
/**
* {@inheritDoc}
* 这个类会返回 SqlSessionFactory
* 并且会调用afterPropertiesSet() 方法
* 这个方法是在spring对当前类属性设置完成后会执行的方法
* 不过此时也会通过getObject()调用
*/
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
2 afterPropertiesFactory();里面构建了 SqlSessionFactory对象
@Override
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
//构建 sqlSessionFactory
this.sqlSessionFactory = buildSqlSessionFactory();
}
3 执行buildSqlsessionFactory()方法,让我们看看这个里面究竟做了什么
//删除了部分代码,留了些主要的代码
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
//这个是mybatis中解析 配置xml的类
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configuration != null) {
configuration = this.configuration;
if (configuration.getVariables() == null) {
configuration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
configuration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
configuration = new Configuration();
if (this.configurationProperties != null) {
configuration.setVariables(this.configurationProperties);
}
}
//开始解析mybatis中的配置类,springboot 中不会执行xmlConfigBuilder ==null
// ===========要点1===========
if (xmlConfigBuilder != null) {
try {
l
xmlConfigBuilder.parse();
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " +
this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));
//这个地方开始遍历解析我们写的 各种xml文件
if (!isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
//解析xml的类
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, mapperLocation.toString(), configuration.getSqlFragments());
//开始解析
// ==============要点2=========
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
以上都是在SqlSessionFactoryBean中执行的,下面的我们就要点1(解析mybatis-config.xml)和要点2(解析编写的xml)做介绍
同时现在源码是属于 mybatis的,不在是spring 和myabtis整合的jar中了
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
1 XMLConfigBuilder类中的xmlConfigBuilder.parse(); 方法 要点1
public Configuration parse() {
//判断是否解析过
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
//开始解析配置文件
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
2 parseConfiguration(parser.evalNode("/configuration"));方法解析
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
//获取所有settings标签下的配置信息
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);
}
}
//设置一些参数配置方法
private void settingsElement(Properties props) throws Exception {
configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
//默认开启二级缓存
configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
//设置代理类并创建
configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
//是否在insert语句中返回主键: 默认是false
configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
//设置默认的ExcutorType
<ul>
<li><code>ExecutorType.SIMPLE</code>:这个执行器类型不做特殊的事情。
它为每个语句的执行创建一个新的预处理语句。</li>
<li><code>ExecutorType.REUSE</code>:这个执行器类型会复用预处理语句。</li>
<li><code>ExecutorType.BATCH</code>:这个执行器会批量执行所有更新语句,
如果 SELECT 在它们中间执行,必要时请把它们区分开来以保证行为的易读性。</li>
</ul>
configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
@SuppressWarnings("unchecked")
Class<? extends TypeHandler> typeHandler = (Class<? extends TypeHandler>)resolveClass(props.getProperty("defaultEnumTypeHandler"));
configuration.setDefaultEnumTypeHandler(typeHandler);
configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
configuration.setLogPrefix(props.getProperty("logPrefix"));
@SuppressWarnings("unchecked")
Class<? extends Log> logImpl = (Class<? extends Log>)resolveClass(props.getProperty("logImpl"));
configuration.setLogImpl(logImpl);
configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
}
由上面的配置可见: mybatis中二级缓存(不清楚的可以网上看看)在全局是开启的,顺便说一句,如果在mapper.xml加了cache标签才表示在当前的xml中可以使用二级缓存,后面解析xml是会讲3
3 要点2 解析开始 XMLMapperBuilder.xmlMapperBuilder.parse();
public void parse() {
//判断当前resource是否解析过:F:/xxx/data/target/classes/xxx/BillTypeDOMapper.xml
if (!configuration.isResourceLoaded(resource)) {
//解析mapper.xml标签以及其子标签
configurationElement(parser.evalNode("/mapper"));
//讲当前xml加入configuration
configuration.addLoadedResource(resource);
//绑定Namespace里面的Class对象
//Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
// 用于后面获取mapper的代理对象(SqlSession.getMapper(DemoMapper.class));
bindMapperForNamespace();
}
//重新解析之前解析不了的节点: 因为我们写的sql语句时无顺序的,xml解析是从上到下的,如果我们写的标签顺讯不一致
//就会出现异常,并且将这些出现异常的重写解析一遍
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
4 解析xml中的配置信息 configurationElement(parser.evalNode("/mapper")); 这个基本上就涉及了全部的解析了
private void configurationElement(XNode context) {
try {
//mapper接口的全路径: com.xxx.mapper.xxx.BillTypeDOMapper
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
//设置当前的namespace名称
builderAssistant.setCurrentNamespace(namespace);
//cache-ref和cache都是开启二级缓存 namespace级别
//一般来说,我们会为每一个单表创建一个单独的映射文件,如果存在涉及多个表的查询的话,
// 由于Mybatis的二级缓存是基于namespace的,
// 多表查询语句所在的namspace无法感应到其他namespace中的语句对多表查询中涉及的表进行了修改,引发脏数据问题
//两者的区别就是第一个无法设置一些配置,后面的可以设置,具体设置参数看下面的代码
cacheRefElement(context.evalNode("cache-ref"));
//判断是够使用二级缓存 并且获取二级缓存的配置
cacheElement(context.evalNode("cache"));
//入参映射java对象类型: 现在很少用
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
//出参映射解析: 会将数据库列名与javaDO实体对象的关系也解析出来 resultMap标签解析
resultMapElements(context.evalNodes("/mapper/resultMap"));
//解析<sql> 标签 并放进存放sql的一个map中 key是xml文件全路径+标签的ID
sqlElement(context.evalNodes("/mapper/sql"));
//解析select|insert|update|delete 标签并且生成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);
}
}
下面我就把一些认为重要的摘出来:
一 buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
private void buildStatementFromContext(List<XNode> list) {
//databaseId现在一般为空
if (configuration.getDatabaseId() != null) {
buildStatementFromContext(list, configuration.getDatabaseId());
}
buildStatementFromContext(list, null);
}
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
for (XNode context : list) {
//xml中的sql语句一个一个解析
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
//开始解析
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
二 XMLStatementBuilder.parseStatementNode(); 解析语句
public void parseStatementNode() {
String id = context.getStringAttribute("id");
String databaseId = context.getStringAttribute("databaseId");
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
//select语句时:flushCache默认为false,表示任何时候语句被调用,都不会去清空本地缓存和二级缓存。
//非select语句时 默认是true 表示会清空缓存
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
//是否使用二级缓存: select是使用二级缓存(默认: true)
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());
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
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;
}
//解析sql语句,并且判断是不是动态sql(含有${}或者一些其它标签)
--注意 此时动态标签不会讲#{}替换,如果不是动态的那么 将#{} 替换成占位符
//非动态 比如: select * from test id=#{id,LONG}
变成 select * from test id=?
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
//获取sql语句的类型: 默认是预编译类型(PREPARED)
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String resultType = context.getStringAttribute("resultType");
Class<?> resultTypeClass = resolveClass(resultType);
String resultMap = context.getStringAttribute("resultMap");
String resultSetType = context.getStringAttribute("resultSetType");
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
if (resultSetTypeEnum == null) {
resultSetTypeEnum = configuration.getDefaultResultSetType();
}
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
String resultSets = context.getStringAttribute("resultSets");
//组装MappedStatment
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
三 解析动态语句和非动态语句 LanguageDriver(接口).langDriver.createSqlSource(configuration, context, parameterTypeClass);
实现类XMLLanguageDriver来执行
@Override
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
//会初始化哪些属于动态语句
XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
return builder.parseScriptNode();
}
//以下属于动态语句
private void initNodeHandlerMap() {
nodeHandlerMap.put("trim", new TrimHandler());
nodeHandlerMap.put("where", new WhereHandler());
nodeHandlerMap.put("set", new SetHandler());
nodeHandlerMap.put("foreach", new ForEachHandler());
nodeHandlerMap.put("if", new IfHandler());
nodeHandlerMap.put("choose", new ChooseHandler());
nodeHandlerMap.put("when", new IfHandler());
nodeHandlerMap.put("otherwise", new OtherwiseHandler());
nodeHandlerMap.put("bind", new BindHandler());
}
//解析语句
public SqlSource parseScriptNode() {
//解析 并判断是不是动态语句
MixedSqlNode rootSqlNode = parseDynamicTags(context);
SqlSource sqlSource;
if (isDynamic) {
//不做变动
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
} else {
//获得sql语句: 并且将 #{} 替换成 ?(占位符)
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
}
return sqlSource;
}
五 XMLScriptBuilder.parseScriptNode 判断sql是不是动态语句
protected MixedSqlNode parseDynamicTags(XNode node) {
List<SqlNode> contents = new ArrayList<>();
NodeList children = node.getNode().getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
XNode child = node.newXNode(children.item(i));
//判断是text或者CDATA表达式
if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
String data = child.getStringBody("");
//下面的对象是用来判断是否是动态sql
TextSqlNode textSqlNode = new TextSqlNode(data);
//${}和一些if foreach,trim等等都是是动态的(isDynamic)
textSqlNode.isDynamic() 里面解析 data 判断是否含有${}
if (textSqlNode.isDynamic()) {
contents.add(textSqlNode);
//赋值是否是动态语句
isDynamic = true;
} else {
contents.add(new StaticTextSqlNode(data));
}
} else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
//解析标签
//比如:<if test="extInfo != null">
// ext_info,
// </if> 或者 <foreach><foreach/> 等等
//nodeHandlerMap map中包含了所有标签类型
String nodeName = child.getNode().getNodeName();
//NodeHandler 有多个实现类 nodeHandlerMap可见 分别解析不同的标签
//比如:ForEachHandler,TrimHandler,WhereHandler等等
NodeHandler handler = nodeHandlerMap.get(nodeName);
if (handler == null) {
throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
}
//解析的sql语句
handler.handleNode(child, contents);
isDynamic = true;
}
}
return new MixedSqlNode(contents);
}
以上就是mybatis和springboot整合时解析xml的过程,如果有不对的地方帮忙指正
下一节写springboot sql语句执行,参数绑定过程