MyBatis的強大特性之一即是它的動態SQL,之前拼接的時候須要注意的空格、列表最後的逗號等,如今均可以不用手動處理了,MyBatis採用功能強大的基於OGNL的表達式來實現,下面主要介紹下。spring
if是最經常使用的判斷語句,主要用於實現某些簡單的條件選擇。基本使用示例以下:sql
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user where 1=1 <if test="name != null and name != ''"> and name = #{name} </if> <if test="age != null "> and age = #{age} </if> </select>
上面的例子中使用了「1=1」,是爲了不後續條件不知足時候報錯,那有沒有辦法避免這種寫法呢?
固然有,就是接下來要說的<where>,<where>標籤會自動判斷若是包含的標籤中有返回值的話,就在sql中插入一個‘where’,若是where標籤最後返回的內容是以and 或者or開頭的,也會被自動移除掉,上面例子中換成「where」標籤後寫法以下:數組
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user <where> <if test="name != null and name != ''"> and name = #{name} </if> <if test="age != null "> and age = #{age} </if> </where> </select>
<trim>的做用是去除特殊的字符串,它的prefix屬性表明語句的前綴,prefixOverrides屬性表明須要去除的哪些特殊字符串,prefixOverrides屬性會忽略經過管道分隔的文本序列(注意此例中的空格也是必要的),後綴的處理和前綴同樣。springboot
trim標籤的主要屬性以下mybatis
舉兩個例子。架構
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user <trim prefix="WHERE" prefixOverrides="AND |OR " > <if test="name != null and name != ''"> and name = #{name} </if> <if test="sex != null "> or sex = #{sex} </if> <if test="age != null "> and age = #{age} </if> </trim> </select>
<update id="update" parameterType="Object"> UPDATE user <trim suffix=" SET " suffixOverrides=","> <if test="id != null ">id=#{id},</if> <if test="name != null ">name=#{name},</if> <if test="age != null ">age=#{age},</if> </trim> WHERE ID=#{id} </update>
<foreach>的做用是遍歷集合,它可以很好地支持數組和List、Set接口的集合的遍歷,每每和sql中的in組合比較多。ide
foreach標籤的主要屬性以下微服務
舉個例子:spa
<select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User"> select * from user where id in <foreach item="id" index="index" collection="userList" open="(" separator="," close=")"> #{id} </foreach> </select>
到此MyBatis的動態SQL的經常使用功能已經介紹完了,有問題歡迎留言溝通哦! code
推薦閱讀
1.一分鐘帶你瞭解下Spring Security!
2.一分鐘帶你學會利用mybatis-generator自動生成代碼!
3.手把手帶你實戰下Spring的七種事務傳播行爲
4.SpringBoot系列-整合Mybatis(註解方式)
5.SpringBoot系列-整合Mybatis(XML配置方式)
Java碎碎念,一個堅持原創的公衆號,爲您提供一系列系統架構、微服務、Java、SpringBoot、SpringCloud等高質量技術文章。
若是以爲文章不錯,但願能夠隨手轉發或者」在看「哦,很是感謝哈!
關注下方公衆號後回覆「1024」,有驚喜哦!