Mybatis框架之動態SQL書寫方式小結
動態SQL簡介
動態SQL是Mybatis框架中強大特性之一。在一些組合查詢頁面,需要根據用戶輸入的查詢條件生成不同的查詢SQL,這在JDBC或其他相似框架中需要在代碼中拼寫SQL,經常容易出錯,在Mybatis框架中可以解決這種問題。
使用動態SQL元素與JSTL相似,它允許我們在XML中構建不同的SQL語句。常用元素為:
判斷元素:if,choose
關鍵字元素:where,set,trim
循環元素:foreach
if元素
if元素是簡單的條件判斷邏輯,滿足指定條件時追加if元素內的SQL,不滿足條件時不追加。格式為:
<select....>
SQL語句1
<if test = "條件表達式">
SQL語句2
</if>
</select>
if元素最常見的使用是在where字句部分,根據不同情況追加不同的SQL條件。示例為:
<select id = "findByDeptNo" parameterType = "Emp" resultType = "Emp">
select * from Emp
<if test = "deptno != null">
where DEPTNO = #{deptno}
</if>
</select>
choose元素
choose元素的作用就相當於java中的switch語句,基本上跟JSTL中的choose作用和用法是一樣的,通常與when和otherwise搭配使用。格式為:
<select ..>
SQL語句1
<choose>
<when test = "條件表達式">
SQL語句2
</when>
<otherwise>
SQL語句3
</otherwise>
</choose>
</select>
choose元素的使用示例為:
<select id = "findBySal" resultType = "Emp" parameterType = "Emp">
select * from Emp where
<choose>
<when test = "sal>2000">
SAL>=#{sal}
</when>
<otherwise>
SAL>=2000
</otherwise>
</choose>
</select>
where元素
where元素主要用於簡化查詢語句中where部分的條件判斷。where元素可以在<where>元素所在位置輸出一個where關鍵字,而且還可以將後面條件多余的and或or關鍵字去除。格式為:
<select..>
select 字段 from 表
<where>
動態追加條件
</where>
</select>
where元素的代碼示例為:
<select id = "findByCondition" resultType = "Emp" parameterType = "Emp">
select * from Emp
<where>
<if test = "deptno != null">
DEPTNO = #{deptno}
</if>
<choose>
<when test = "sal>2000">
and SAL >= #{sal}
</when>
<otherwise>
and SAL >= 2000
</otherwise>
</choose>
</where>
</select>
set元素
set元素主要是用在更新操作的時候,他的主要功能和where元素相似,主要是在<set>元素所在位置輸出一個set關鍵字,而且還可以去除內容結尾中無關的逗號。有了set元素可以動態的更新那些修改了的字段。使用格式為:
<update...>
update表
<set>
動態追加更新字段
</set>
</update>
set元素代碼示例為:
<update id = "updateEmp" parameterType = "Emp">
update Emp
<set>
<if test = "ename != null">
SAL = #{sal}
</if>
<if test = "comm != null">
COMM = #{comm}
</if>
<if test = "deptno != null">
DEPTNO = #{deptno}
</if>
</set>
where EMPNO = #{empno}
</update>
trim元素
trim元素主要功能為:
可以在自己包含的內容前加上某些前綴,也可以在其後加上某些後綴,與之對應的屬性是prefix和suffix;
可以把包含內容的首部某些內容過濾,即忽略。也可以把尾部的某些內容過濾,對應的屬性是prefixOverrides和suffixOverrides;
正因為trim有這些功能,所以我們可以非常簡單的利用trim代替where和set元素功能。
trim元素應用示例為:
<!-- 等價於where元素 -->
<trim prefix = "WHERE" prefixOverrides = "AND | OR">
....
</trim>
<!-- 等價於set元素 -->
<trim prefix = "SET" suffixOverrides = ",">
...
</trim>
foreach元素
foreach元素實現了循環邏輯,可以進行一個集合的叠代。主要用於在構建in條件中,foreach使用示例為:
<select ..>
select字段 from 表 where 字段 in
<foreach collection = "集合" item = "叠代變量" open = "(" separator = "," close = ")">
#{叠代變量}
</foreach>
</select>
foreach元素非常強大,它允許指定一個集合,聲明集合項和索引變量,這些變量可以用在元素體內。它也允許指定開放和關閉的字符串,在叠代之間放置分隔符。
foreach元素代碼示例為:
<select id = "findByDeptNos" resultyType = "Emp" parameterType = "Emp">
select * from Emp
<if test = "deptnos != null">
where DEPTNO in
<foreach collection = "deptnos" item = "dno" open = "(" close = ")" separator = ",">
#{dno}
</foreach>
</if>
</select>
Mybatis框架之動態SQL書寫方式小結