上篇文章簡單介紹了mybatis的查詢,至此,CRUD都已講完。本文將介紹mybatis強大的動態SQL。 html
那麼,問題來了: 什麼是動態SQL? 動態SQL有什麼做用? java
傳統的使用JDBC的方法,相信你們在組合複雜的的SQL語句的時候,須要去拼接,稍不注意哪怕少了個空格,都會致使錯誤。Mybatis的動態SQL功能正是爲了解決這種問題, 其經過 if, choose, when, otherwise, trim, where, set, foreach標籤,可組合成很是靈活的SQL語句,從而提升開發人員的效率。下面就去感覺Mybatis動態SQL的魅力吧: 數組
1. if: 大家能判斷,我也能判斷! session
做爲程序猿,誰不懂 if ! 在mybatis中也能用 if 啦: mybatis
<select id="findUserById" resultType="user"> select * from user where <if test="id != null"> id=#{id} </if> and deleteFlag=0; </select>
上面例子: 若是傳入的id 不爲空, 那麼纔會SQL才拼接id = #{id}。 這個相信你們看同樣就能明白,很少說。 app
細心的人會發現一個問題:「你這不對啊! 要是你傳入的id爲null, 那麼你這最終的SQL語句不就成了 select * from user where and deleteFlag=0, 這語句有問題!」 dom
是啊,這時候,mybatis的 where 標籤就該隆重登場啦: ide
2. where, 有了我,SQL語句拼接條件神馬的都是浮雲! 測試
我們經過where改造一下上面的例子: spa
<select id="findUserById" resultType="user"> select * from user <where> <if test="id != null"> id=#{id} </if> and deleteFlag=0; </where> </select>
有些人就要問了: 「你這都是些什麼玩意兒! 跟上面的相比, 不就是多了個where標籤嘛! 那這個還會不會出現 select * from user where and deleteFlag=0 ?」
的確,從表面上來看,就是多了個where標籤而已, 不過實質上, mybatis是對它作了處理,當它遇到AND或者OR這些,它知道怎麼處理。其實咱們能夠經過 trim 標籤去自定義這種處理規則。
3. trim : 個人地盤,我作主!
上面的where標籤,其實用trim 能夠表示以下:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
它的意思就是: 當WHERE後緊隨AND或則OR的時候,就去除AND或者OR。 除了WHERE之外, 其實還有一個比較經典的實現,那就是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後面那逗號會致使出錯啊!」
是的,這時候,就能夠用mybatis爲咱們提供的set 標籤了。下面是經過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> </set> <where> <if test="id != null"> id = #{id} </if> and deleteFlag = 0; </where> </update>
這個用trim 可表示爲:
<trim prefix="SET" suffixOverrides=","> ... </trim>
WHERE是使用的 prefixOverrides(前綴), SET是使用的 suffixOverrides (後綴), 看明白了吧!
5. foreach: 你有for, 我有foreach, 不要覺得就你才屌!
java中有for, 可經過for循環, 一樣, mybatis中有foreach, 可經過它實現循環,循環的對象固然主要是java容器和數組。
<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>
foreach的主要用在構建in條件中,它能夠在SQL語句中進行迭代一個集合。foreach元素的屬性主要有 item,index,collection,open,separator,close。item表示集合中每個元素進行迭代時的別名,index指 定一個名字,用於表示在迭代過程當中,每次迭代到的位置,open表示該語句以什麼開始,separator表示在每次進行迭代之間以什麼符號做爲分隔 符,close表示以什麼結束,在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,可是在不一樣狀況 下,該屬性的值是不同的
3. 若是傳入的參數是多個的時候,咱們就須要把它們封裝成一個Map了,固然單參數也能夠封裝成map,實際上若是你在傳入參數的時候,在breast裏面也是會把它封裝成一個Map的,map的key就是參數名,因此這個時候collection屬性值就是傳入的List或array對象在本身封裝的map裏面的key
下面分別來看看上述三種狀況的示例代碼:
1.單參數List的類型:
<select id="dynamicForeachTest" resultType="Blog"> select * from t_blog where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
@Test public void dynamicForeachTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(3); ids.add(6); List<Blog> blogs = blogMapper.dynamicForeachTest(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
<select id="dynamicForeach2Test" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
@Test public void dynamicForeach2Test() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); int[] ids = new int[] {1,3,6,9}; List<Blog> blogs = blogMapper.dynamicForeach2Test(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
<select id="dynamicForeach3Test" resultType="Blog"> select * from t_blog where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
@Test public void dynamicForeach3Test() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); final List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); ids.add(6); ids.add(7); ids.add(9); Map<String, Object> params = new HashMap<String, Object>(); params.put("ids", ids); params.put("title", "中國"); List<Blog> blogs = blogMapper.dynamicForeach3Test(params); for (Blog blog : blogs) System.out.println(blog); session.close(); }
將一個 List 實例或者數組做爲參數對象傳給 MyBatis,當這麼作的時候,MyBatis 會自動將它包裝在一個 Map 中並以名稱爲鍵。List 實例將會以「list」做爲鍵,而數組實例的鍵將是「array」。一樣, 當循環的對象爲map的時候,index其實就是map的key。
6. choose: 我選擇了你,你選擇了我!
Java中有switch, mybatis有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>
以上例子中: 當title和author都不爲null的時候, 那麼選擇二選一(前者優先), 若是都爲null, 那麼就選擇 otherwise中的, 若是tilte和author只有一個不爲null, 那麼就選擇不爲null的那個。
縱觀mybatis的動態SQL, 強大而簡單, 相信你們簡單看一下就能使用了。