一、概述
傳統(tǒng)的使用JDBC的方法,相信大家在組合復(fù)雜的的SQL語句的時(shí)候,需要去拼接,稍不注意哪怕少了個(gè)空格,都會(huì)導(dǎo)致錯(cuò)誤。Mybatis的動(dòng)態(tài)SQL功能正是為了解決這種問題, 其通過 if, choose, when, otherwise, trim, where, set, foreach標(biāo)簽,可組合成非常靈活的SQL語句,從而提高開發(fā)人員的效率。
二、動(dòng)態(tài)SQL標(biāo)簽
1 if
<select id="findUserById" resultType="user">
select * from user where
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</select>
上面例子: 如果傳入的id 不為空, 那么才會(huì)SQL才拼接id = #{id}。 這個(gè)相信大家看一樣就能明白,不多說。細(xì)心的人會(huì)發(fā)現(xiàn)一個(gè)問題:“你這不對啊! 要是你傳入的id為null, 那么你這最終的SQL語句不就成了 select * from user where and deleteFlag=0, 這語句有問題!”
是啊,這時(shí)候,mybatis的 where 標(biāo)簽就該隆重登場啦。
2 where
<select id="findUserById" resultType="user">
select * from user
<where>
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</where>
</select>
有些人就要問了: “你這都是些什么玩意兒! 跟上面的相比, 不就是多了個(gè)where標(biāo)簽嘛! 那這個(gè)還會(huì)不會(huì)出現(xiàn) select * from user where and deleteFlag=0 ?”
的確,從表面上來看,就是多了個(gè)where標(biāo)簽而已, 不過實(shí)質(zhì)上, mybatis是對它做了處理,當(dāng)它遇到AND或者OR這些,它知道怎么處理。其實(shí)我們可以通過 trim 標(biāo)簽去自定義這種處理規(guī)則。
3 trim
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
它的意思就是:當(dāng)WHERE后緊隨AND或則OR的時(shí)候,就去除AND或者OR。 除了WHERE以外, 其實(shí)還有一個(gè)比較經(jīng)典的實(shí)現(xiàn),那就是SET。
4 set
<update id="updateUser" parameterType="com.dy.entity.User">
update user set
<if test="name != null">
name = #{name},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != null">
age = #{age}
</if>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>
問題又來了: “如果我只有name不為null, 那么這SQL不就成了 update set name = #{name}, where ........ ? 你那name后面那逗號(hào)會(huì)導(dǎo)致出錯(cuò)??!”
是的,這時(shí)候,就可以用mybatis為我們提供的set 標(biāo)簽了。下面是通過set標(biāo)簽改造后:
<update id="updateUser" parameterType="com.dy.entity.User">
update user
<set>
<if test="name != null">name = #{name},</if>
<if test="password != null">password = #{password},</if>
<if test="age != null">age = #{age},</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>
這個(gè)用trim 可表示為:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
WHERE是使用的 prefixOverrides(前綴), SET是使用的 suffixOverrides (后綴)。
5 foreach
MyBatis中有foreach, 可通過它實(shí)現(xiàn)循環(huán),循環(huán)的對象當(dāng)然主要是java容器和數(shù)組。
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
將一個(gè) List 實(shí)例或者數(shù)組作為參數(shù)對象傳給 MyBatis:當(dāng)這么做的時(shí)候,MyBatis 會(huì)自動(dòng)將它包裝在一個(gè) Map 中并以名稱為鍵。List 實(shí)例將會(huì)以“l(fā)ist”作為鍵,而數(shù)組實(shí)例的鍵將是“array”。同樣,當(dāng)循環(huán)的對象為map的時(shí)候,index其實(shí)就是map的key。
6 choose
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
以上例子中: 當(dāng)title和author都不為null的時(shí)候, 那么選擇二選一(前者優(yōu)先), 如果都為null, 那么就選擇 otherwise中的, 如果tilte和author只有一個(gè)不為null, 那么就選擇不為null的那個(gè)。
三 關(guān)于動(dòng)態(tài)SQL的接口和類
1.SqlNode
簡單理解就是xml中的每個(gè)標(biāo)簽,比如上述sql的update,trim,if標(biāo)簽:
public interface SqlNode {
boolean apply(DynamicContext context);
}

2. SqlSource
SqlSource是Sql源接口,代表從xml文件或注解映射的sql內(nèi)容,主要就是用于創(chuàng)建BoundSql,有實(shí)現(xiàn)類DynamicSqlSource(動(dòng)態(tài)Sql源),StaticSqlSource(靜態(tài)Sql源)等:
public interface SqlSource {
BoundSql getBoundSql(Object parameterObject);
}

3.BoundSql
封裝mybatis最終產(chǎn)生sql的類,包括sql語句,參數(shù),參數(shù)源數(shù)據(jù)等參數(shù):

4.XNode
一個(gè)Dom API中的Node接口的擴(kuò)展類:

5.BaseBuilder

XMLConfigBuilder:解析mybatis中configLocation屬性中的全局xml文件,內(nèi)部會(huì)使用XMLMapperBuilder解析各個(gè)xml文件。
XMLMapperBuilder:遍歷mybatis中mapperLocations屬性中的xml文件中每個(gè)節(jié)點(diǎn)的Builder,比如user.xml,內(nèi)部會(huì)使用XMLStatementBuilder處理xml中的每個(gè)節(jié)點(diǎn)。
XMLStatementBuilder:解析xml文件中各個(gè)節(jié)點(diǎn),比如select,insert,update,delete節(jié)點(diǎn),內(nèi)部會(huì)使用XMLScriptBuilder處理節(jié)點(diǎn)的sql部分,遍歷產(chǎn)生的數(shù)據(jù)會(huì)丟到Configuration的mappedStatements中。
XMLScriptBuilder:解析xml中各個(gè)節(jié)點(diǎn)sql部分的Builder。
6.LanguageDriver
該接口主要的作用就是構(gòu)造sql:

簡單分析下XMLLanguageDriver(處理xml中的sql,RawLanguageDriver處理靜態(tài)sql):XMLLanguageDriver內(nèi)部會(huì)使用XMLScriptBuilder解析xml中的sql部分。
四 源碼分析
Spring與Mybatis整合的時(shí)候需要配置SqlSessionFactoryBean,該配置會(huì)加入數(shù)據(jù)源和mybatis xml配置文件路徑等信息:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatisConfig.xml"/>
<property name="mapperLocations" value="classpath*:org/format/dao/*.xml"/>
</bean>
SqlSessionFactoryBean實(shí)現(xiàn)了Spring的InitializingBean接口,InitializingBean接口的afterPropertiesSet方法中會(huì)調(diào)用buildSqlSessionFactory方法 該方法內(nèi)部會(huì)使用XMLConfigBuilder解析屬性configLocation中配置的路徑,還會(huì)使用XMLMapperBuilder屬性解析mapperLocations屬性中的各個(gè)xml文件。部分源碼如下:

由于XMLConfigBuilder內(nèi)部也是使用XMLMapperBuilder,我們就看看XMLMapperBuilder的解析細(xì)節(jié):
由于XMLConfigBuilder內(nèi)部也是使用XMLMapperBuilder,我們就看看XMLMapperBuilder的解析細(xì)節(jié):


增刪改查節(jié)點(diǎn)的解析:

XMLStatementBuilder的解析:

默認(rèn)會(huì)使用XMLLanguageDriver創(chuàng)建SqlSource(Configuration構(gòu)造函數(shù)中設(shè)置)。
XMLLanguageDriver創(chuàng)建SqlSource:

XMLScriptBuilder解析sql:

得到SqlSource之后,會(huì)放到Configuration中,有了SqlSource,就能拿BoundSql了,BoundSql可以得到最終的sql。
五 實(shí)例分析
以下面的xml解析大概說下parseDynamicTags的解析過程
<update id="update" parameterType="org.format.dynamicproxy.mybatis.bean.User">
UPDATE users
<trim prefix="SET" prefixOverrides=",">
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age != null and age != ''">
, age = #{age}
</if>
<if test="birthday != null and birthday != ''">
, birthday = #{birthday}
</if>
</trim>
where id = ${id}
</update>
parseDynamicTags方法的返回值是一個(gè)List,也就是一個(gè)Sql節(jié)點(diǎn)集合。SqlNode本文一開始已經(jīng)介紹,分析完解析過程之后會(huì)說一下各個(gè)SqlNode類型的作用。
首先根據(jù)update節(jié)點(diǎn)(Node)得到所有的子節(jié)點(diǎn),分別是3個(gè)子節(jié)點(diǎn):
(1) 文本節(jié)點(diǎn) \n UPDATE users
(2) trim子節(jié)點(diǎn) ...
(3) 文本節(jié)點(diǎn) \n where id = #{id}
遍歷各個(gè)子節(jié)點(diǎn):
(1) 如果節(jié)點(diǎn)類型是文本或者CDATA,構(gòu)造一個(gè)TextSqlNode或StaticTextSqlNode;
(2) 如果節(jié)點(diǎn)類型是元素,說明該update節(jié)點(diǎn)是個(gè)動(dòng)態(tài)sql,然后會(huì)使用NodeHandler處理各個(gè)類型的子節(jié)點(diǎn)。這里的NodeHandler是XMLScriptBuilder的一個(gè)內(nèi)部接口,其實(shí)現(xiàn)類包括TrimHandler、WhereHandler、SetHandler、IfHandler、ChooseHandler等。看類名也就明白了這個(gè)Handler的作用,比如我們分析的trim節(jié)點(diǎn),對應(yīng)的是TrimHandler;if節(jié)點(diǎn),對應(yīng)的是IfHandler...這里子節(jié)點(diǎn)trim被TrimHandler處理,TrimHandler內(nèi)部也使用parseDynamicTags方法解析節(jié)點(diǎn)。
遇到子節(jié)點(diǎn)是元素的話,重復(fù)以上步驟:
trim子節(jié)點(diǎn)內(nèi)部有7個(gè)子節(jié)點(diǎn),分別是文本節(jié)點(diǎn)、if節(jié)點(diǎn)、是文本節(jié)點(diǎn)、if節(jié)點(diǎn)、是文本節(jié)點(diǎn)、if節(jié)點(diǎn)、文本節(jié)點(diǎn)。文本節(jié)點(diǎn)跟之前一樣處理,if節(jié)點(diǎn)使用IfHandler處理。遍歷步驟如上所示,下面我們看下幾個(gè)Handler的實(shí)現(xiàn)細(xì)節(jié)。
IfHandler處理方法也是使用parseDynamicTags方法,然后加上if標(biāo)簽必要的屬性:
private class IfHandler implements NodeHandler {
public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
List<SqlNode> contents = parseDynamicTags(nodeToHandle);
MixedSqlNode mixedSqlNode = new MixedSqlNode(contents);
String test = nodeToHandle.getStringAttribute("test");
IfSqlNode ifSqlNode = new IfSqlNode(mixedSqlNode, test);
targetContents.add(ifSqlNode);
}
}
TrimHandler處理方法也是使用parseDynamicTags方法,然后加上trim標(biāo)簽必要的屬性:
private class TrimHandler implements NodeHandler {
public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
List<SqlNode> contents = parseDynamicTags(nodeToHandle);
MixedSqlNode mixedSqlNode = new MixedSqlNode(contents);
String prefix = nodeToHandle.getStringAttribute("prefix");
String prefixOverrides = nodeToHandle.getStringAttribute("prefixOverrides");
String suffix = nodeToHandle.getStringAttribute("suffix");
String suffixOverrides = nodeToHandle.getStringAttribute("suffixOverrides");
TrimSqlNode trim = new TrimSqlNode(configuration, mixedSqlNode, prefix, prefixOverrides, suffix, suffixOverrides);
targetContents.add(trim);
}
}
以上update方法最終通過parseDynamicTags方法得到的SqlNode集合如下:

trim節(jié)點(diǎn):

由于這個(gè)update方法是個(gè)動(dòng)態(tài)節(jié)點(diǎn),因此構(gòu)造出了DynamicSqlSource。DynamicSqlSource內(nèi)部就可以構(gòu)造sql了:

DynamicSqlSource內(nèi)部的SqlNode屬性是一個(gè)MixedSqlNode。然后我們看看各個(gè)SqlNode實(shí)現(xiàn)類的apply方法。下面分析一下各個(gè)SqlNode實(shí)現(xiàn)類的apply方法實(shí)現(xiàn):
MixedSqlNode:MixedSqlNode會(huì)遍歷調(diào)用內(nèi)部各個(gè)sqlNode的apply方法
public boolean apply(DynamicContext context) {
for (SqlNode sqlNode : contents) {
sqlNode.apply(context);
}
return true;
}
StaticTextSqlNode:直接append sql文本。
public boolean apply(DynamicContext context) {
context.appendSql(text);
return true;
}
IfSqlNode:這里的evaluator是一個(gè)ExpressionEvaluator類型的實(shí)例,內(nèi)部使用了OGNL處理表達(dá)式邏輯。
public boolean apply(DynamicContext context) {
if (evaluator.evaluateBoolean(test, context.getBindings())) {
contents.apply(context);
return true;
}
return false;
}
TrimSqlNode:
public boolean apply(DynamicContext context) {
FilteredDynamicContext filteredDynamicContext = new FilteredDynamicContext(context);
boolean result = contents.apply(filteredDynamicContext);
filteredDynamicContext.applyAll();
return result;
}
public void applyAll() {
sqlBuffer = new StringBuilder(sqlBuffer.toString().trim());
String trimmedUppercaseSql = sqlBuffer.toString().toUpperCase(Locale.ENGLISH);
if (trimmedUppercaseSql.length() > 0) {
applyPrefix(sqlBuffer, trimmedUppercaseSql);
applySuffix(sqlBuffer, trimmedUppercaseSql);
}
delegate.appendSql(sqlBuffer.toString());
}
private void applyPrefix(StringBuilder sql, String trimmedUppercaseSql) {
if (!prefixApplied) {
prefixApplied = true;
if (prefixesToOverride != null) {
for (String toRemove : prefixesToOverride) {
if (trimmedUppercaseSql.startsWith(toRemove)) {
sql.delete(0, toRemove.trim().length());
break;
}
}
}
if (prefix != null) {
sql.insert(0, " ");
sql.insert(0, prefix);
}
}
}
TrimSqlNode的apply方法也是調(diào)用屬性contents(一般都是MixedSqlNode)的apply方法,按照實(shí)例也就是7個(gè)SqlNode,都是StaticTextSqlNode和IfSqlNode。 最后會(huì)使用FilteredDynamicContext過濾掉prefix和suffix。