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」,是爲了不後續條件不知足時候報錯,那有沒有辦法避免這種寫法呢?
固然有,就是接下來要說的
<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標籤的主要屬性以下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標籤的主要屬性以下微服務
舉個例子:code
<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的經常使用功能已經介紹完了,有問題歡迎留言溝通哦!xml
推薦閱讀
1.一分鐘帶你瞭解下Spring Security!
2.一分鐘帶你學會利用mybatis-generator自動生成代碼!
3.手把手帶你實戰下Spring的七種事務傳播行爲
4.SpringBoot系列-整合Mybatis(註解方式)
5.SpringBoot系列-整合Mybatis(XML配置方式)
Java碎碎念,一個堅持原創的公衆號,爲您提供一系列系統架構、微服務、Java、SpringBoot、SpringCloud等高質量技術文章。
若是以爲文章不錯,但願能夠隨手轉發或者」在看「哦,很是感謝哈!
關注下方公衆號後回覆「1024」,有驚喜哦!
本文由博客一文多發平臺 OpenWrite 發佈!