MyBatis的動態SQL語句是基於OGNL表達式的。可以方便的在SQL語句中實現某些邏輯,總體說來MyBatis動態SQL語句主要有以下幾類:
1、if語句(簡單的條件判斷)。
2、choose(when,otherwize),相當於Java語言中的switch,與JSTL中的choose很類似。
3、trim(對包含的內容加上prefix,或者suffix等,前綴,后綴)。
4、where(主要是用來簡化SQL語句中where條件判斷的,能智能的處理and or,不必擔心多余導致語法錯誤)。
5、set(主要用於更新時)。
6、foreach(在實現MyBatis in語句查詢時特別有用)。
下面分別介紹這幾種處理方式:
注意:以下測試工程使用的是http://www.cnblogs.com/EasonJim/p/7052368.html這章的例子進行改造的。
一、if語句
在User.xml配置:
<select id="dynamicIfTest" parameterType="Article" resultType="Article"> select * from article where 1 = 1 <if test="title != null"> and title = #{title} </if> <if test="content != null"> and content = #{content} </if> limit 1 </select>
說明:這條語句的意思非常簡單,如果提供了title參數,那么就要滿足title=#{title},同樣如果提供了Content的時候,它們也需要滿足相應的條件,之后就是返回滿足這些條件的所有Article,這是非常有用的一個功能,以往使用其他類型框架或者直接使用JDBC的時候, 如果要達到同樣的選擇效果的時候,就需要拼SQL語句,這是極其麻煩的,比起來,上述的動態SQL就要簡單多了,並且這些參數全部是防止SQL注入的。
在IUserOperation.java配置:
public Article dynamicIfTest(Article article);
測試代碼:
Article inArticle = new Article(); inArticle.setTitle("test_title"); Article outArticle = userOperation.dynamicIfTest(inArticle); System.out.println("id:"+outArticle.getId()+" title:"+outArticle.getTitle()+" content:"+outArticle.getContent());
二、choose(when,otherwize),相當於Java語言中的switch,與JSTL中的choose很類似
在User.xml配置:
<select id="dynamicChooseTest" resultType="Article"> select * from article where 1 = 1 <choose> <when test="title != null"> and title = #{title} </when> <when test="content != null"> and content = #{content} </when> <otherwise> and tile = "test_title" </otherwise> </choose> </select>
說明:when元素表示當when中的條件滿足的時候就輸出其中的內容,跟JAVA中的switch效果差不多的是按照條件的順序,當when中有條件滿足的時候,就會跳出choose,即所有的when和otherwise條件中,只有一個會輸出,當所有的我很條件都不滿足的時候就輸出otherwise中的內容。所以上述語句的意思非常簡單, 當title!=null的時候就輸出and titlte = #{title},不再往下判斷條件,當title為空且content!=null的時候就輸出and content = #{content},當所有條件都不滿足的時候就輸出otherwise中的內容。且這里沒有指定參數的類型parameterType,那么下面的接口文件需要特殊處理。
在IUserOperation.java配置:
public Article dynamicChooseTest( @Param("title") String title, @Param("content") String content);
說明,@Param指定了參數的名稱,如果存在多個參數時,必須使用此注解進行標注,不然無法識別參數,除非參數改成arg0,arg1的順序形式。
測試代碼:
Article outArticle2 = userOperation.dynamicChooseTest("test_title",null); System.out.println("id:"+outArticle2.getId()+" title:"+outArticle2.getTitle()+" content:"+outArticle2.getContent());
三、trim(對包含的內容加上prefix,或者suffix等,前綴,后綴)
在User.xml配置:
<select id="dynamicTrimTest" parameterType="Article" resultType="Article"> select * from article <trim prefix="where" prefixOverrides="and | or"> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="id != null"> or id = #{id} </if> </trim> </select>
說明:trim元素的主要功能是可以在自己包含的內容前加上某些前綴,也可以在其后加上某些后綴,與之對應的屬性是prefix和suffix;可以把包含內容的首部某些內容覆蓋,即忽略,也可以把尾部的某些內容覆蓋,對應的屬性是prefixOverrides和suffixOverrides;正因為trim有這樣的功能,所以也可以非常簡單的利用trim來代替where元素的功能。
在IUserOperation.java配置:
public Article dynamicTrimTest(Article article);
測試代碼:
Article inArticle3 = new Article(); inArticle3.setContent("test_content"); Article outArticle3 = userOperation.dynamicTrimTest(inArticle3); System.out.println("id:"+outArticle3.getId()+" title:"+outArticle3.getTitle()+" content:"+outArticle3.getContent());
四、where(主要是用來簡化SQL語句中where條件判斷的,能智能的處理and or,不必擔心多余導致語法錯誤)
在User.xml配置:
<select id="dynamicWhereTest" parameterType="Article" resultType="Article"> select * from article <where> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> </where> </select>
說明:where元素的作用是會在寫入where元素的地方輸出一個where,另外一個好處是不需要考慮where元素里面的條件輸出是什么樣子的,MyBatis會智能的幫你處理,如果所有的條件都不滿足那么MyBatis就會查出所有的記錄,如果輸出后是and開頭的,MyBatis會把第一個and忽略,當然如果是or開頭的,MyBatis也會把它忽略;此外,在where元素中不需要考慮空格的問題,MyBatis會智能的幫你加上。像上述例子中,如果title=null, 而content != null,那么輸出的整個語句會是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因為MyBatis會智能的把首個and或or給忽略。
在IUserOperation.java配置:
public Article dynamicWhereTest(Article article);
測試代碼:
Article inArticle4 = new Article(); inArticle4.setContent("test_content"); Article outArticle4 = userOperation.dynamicWhereTest(inArticle4); System.out.println("id:"+outArticle4.getId()+" title:"+outArticle4.getTitle()+" content:"+outArticle4.getContent());
五、set(主要用於更新時)
在User.xml配置:
<update id="dynamicSetTest" parameterType="Article"> update article <set> <if test="title != null"> title = #{title}, </if> <if test="content != null"> content = #{content} </if> </set> where id = #{id} </update>
說明:set元素主要是用在更新操作的時候,它的主要功能和where元素其實是差不多的,主要是在包含的語句前輸出一個set,然后如果包含的語句是以逗號結束的話將會把該逗號忽略,如果set包含的內容為空的話則會出錯。有了set元素就可以動態的更新那些修改了的字段。
在IUserOperation.java配置:
public int dynamicSetTest(Article article);
測試代碼:
Article inArticle5 = new Article(); inArticle5.setContent("test_content"); inArticle5.setId(1); int updateRetCout = userOperation.dynamicSetTest(inArticle5); session.commit();//更新必須提交事務,不然不會寫入數據庫 System.out.println("更新受影響的行數:"+updateRetCout);
六、foreach(在實現MyBatis in語句查詢時特別有用)
foreach的主要用在構建in條件中,它可以在SQL語句中進行迭代一個集合。foreach元素的屬性主要有item,index,collection,open,separator,close。item表示集合中每一個元素進行迭代時的別名,index指定一個名字,用於表示在迭代過程中,每次迭代到的位置,open表示該語句以什么開始,separator表示在每次進行迭代之間以什么符號作為分隔符,close表示以什么結束,在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:
- 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list
- 如果傳入的是單參數且參數類型是一個Array數組的時候,collection的屬性值為array
- 如果傳入的參數是多個的時候,就需要把它們封裝成一個Map,當然單參數也可以封裝成Map,實際上如果在傳入參數的時候,在MyBatis里面也是會把它封裝成一個Map的,Map的key就是參數名,所以這個時候collection屬性值就是傳入的List或Array對象在自己封裝的Map里面的key
1、單參數List的類型:
在User.xml配置:
<select id="dynamicForeachTest" resultType="Article"> select * from article where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
在IUserOperation.java配置:
public List<Article> dynamicForeachTest(List<Integer> ids);
測試代碼:
List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(3); ids.add(6); List<Article> articless = userOperation.dynamicForeachTest(ids); for (Article articleTemp : articless) System.out.println("id:"+articleTemp.getId()+" title:"+articleTemp.getTitle()+" content:"+articleTemp.getContent());
2、數組類型的參數:
在User.xml配置:
<select id="dynamicForeach2Test" resultType="Article"> select * from article where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
在IUserOperation.java配置:
public List<Article> dynamicForeach2Test(int[] ids);
測試代碼:
int[] ids2 = {1,3,6}; List<Article> articless2 = userOperation.dynamicForeach2Test(ids2); for (Article articleTemp : articless2) System.out.println("id:"+articleTemp.getId()+" title:"+articleTemp.getTitle()+" content:"+articleTemp.getContent());
3、Map類型的參數:
在User.xml配置:
<select id="dynamicForeach3Test" resultType="Article"> select * from article where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
在IUserOperation.java配置:
public List<Article> dynamicForeach3Test(Map<String, Object> params);
測試代碼:
HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title", "title"); map.put("ids", new int[]{1,3,6}); List<Article> articless3 = userOperation.dynamicForeach3Test(map); for (Article articleTemp : articless3) System.out.println("id:"+articleTemp.getId()+" title:"+articleTemp.getTitle()+" content:"+articleTemp.getContent());
測試工程:https://github.com/easonjim/5_java_example/tree/master/mybatis/test8
參考: