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語句執行,參數綁定過程