mybatis動態標籤
阿新 • • 發佈:2022-03-03
Mybatis動態標籤
1. if標籤
動態條件判斷
<select id="findByCondition" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null">
and username=#{username}
</if>
</select>
2.where標籤
動態where
<select id="findByCondition" resultType="com.one.mybatis.domain.User" parameterType="com.one.mybatis.domain.User"> select * from user <where> <if test="username!=null"> username=#{username} </if> </where> </select>
3. foreach標籤
動態遍歷
<select id="findByIds" parameterType="list" resultType="com.one.mybatis.domain.User">
select * from user where id in
<foreach collection="list" open="(" close=")" item="id" separator=",">
#{id}
</foreach>
</select>
其中:
- collection:collection 屬性的值有三個分別是 list、array、map 三種,分別對應的引數型別為:List、陣列、map 集合
- item :表示在迭代過程中每一個元素的別名
- index :表示在迭代過程中每次迭代到的位置(下標)
- open :字首
- close :字尾
- separator :分隔符,表示迭代時每個元素之間以什麼分隔
4. choose標籤
<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap"> SELECT * from STUDENT WHERE 1=1 <where> <choose> <when test="Name!=null and student!='' "> AND name LIKE CONCAT(CONCAT('%', #{student}),'%') </when> <when test="hobby!= null and hobby!= '' "> AND hobby = #{hobby} </when> <otherwise> AND AGE = 15 </otherwise> </choose> </where> </select>
6. set標籤
使用 set+if 標籤修改後,如果某項為 null 則不進行更新,而是保持資料庫原值。避免因為多於的,出現sql語句語法問題
<update id="updateStudent" parameterType="Object">
UPDATE STUDENT
<set>
<if test="name!=null and name!='' ">
NAME = #{name},
</if>
<if test="hobby!=null and hobby!='' ">
MAJOR = #{major},
</if>
<if test="hobby!=null and hobby!='' ">
HOBBY = #{hobby}
</if>
</set>
WHERE ID = #{id};
</update>
7.trim標籤
格式化sql,屬性有:
- prefix:在trim標籤內sql語句加上字首
- suffix:在trim標籤內sql語句加上字尾
- prefixOverrides:指定去除多餘的字首內容,如:prefixOverrides=“AND | OR”,去除trim標籤內sql語句多餘的字首"and"或者"or"。
- suffixOverrides:指定去除多餘的字尾內容
<!--將where提取出來,並加上“1=1”的查詢條件 -->
select * from student where 1=1
<trim suffixOverrides=",">
<if test="name != null and name != ''">
and NAME = #{name}
</if>
<if test="hobby != null and hobby != ''">
and HOBBY = #{hobby}
</if>
</trim>