帶你了解下MyBatis的動態SQL!
MyBatis的強大特性之一便是它的動態SQL,以前拼接的時候需要注意的空格、列表最后的逗號等,現在都可以不用手動處理了,MyBatis采用功能強大的基于OGNL的表達式來實現,下面主要介紹下。
一、if標簽
if是最常用標簽,經常用在判斷語句上,可以實現某些簡單的條件選擇?;臼褂檬纠缦拢?/p>
- <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>
二、where標簽
上面的例子中使用了“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標簽
trim的作用是去除特殊的字符串,它的prefix屬性代表語句的前綴,prefixOverrides屬性代表需要去除的哪些特殊字符串,prefixOverrides屬性會忽略通過管道分隔的字符,后綴的處理和前綴一樣。
trim標簽的主要屬性如下
- prefix:前綴覆蓋并增加其內容。
- suffix:后綴覆蓋并增加其內容。
- prefixOverrides:前綴判斷的條件。
- suffixOverrides:后綴判斷的條件。
舉兩個例子。
使用前綴屬性
- <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 prefix=" SET " prefixOverrides=",">
- <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標簽
foreach的作用是遍歷集合,它能夠很好地支持數組和List、Set接口的集合的遍歷,往往和sql中的in組合比較多。
foreach標簽的主要屬性如下
- item:表示循環中當前的元素。
- index:表示當前元素在集合的位置下標。
- collection:配置list的屬性名等。
- open和close:配置的是以什么符號將這些集合元素包裝起來。
- separator:配置的是各個元素的間隔符。
舉個例子:
- <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>