1. if標簽
A. 標簽屬性:test —— 表示條件,條件成立就把元素體中的字符串拼接到sql語句中,否則不拼接;
B. 應用場景:通常用於WHERE語句、UPDATE語句、INSERT語句中,通過判斷參數值來決定是否使用某個查詢條件、判斷是否更新某一個字段、判斷是否插入某個字段的值;
C. 示例
2. choose/when/otherwise標簽
A. when標簽中test屬性與if中test類似,按順序判斷when中的條件是否成立,如果有一個成立,則choose結束,當choose中所有when的條件都不滿足時,則執行otherwise中的sql,這個類似於Java的switch語句;
B. 應用場景:當我們並不想應用所有條件,只想從多個選項中選擇一個;
C. 示例
3. trim標簽
A. 應用場景:trim標簽一般用於去除sql語句中多余的and關鍵字、,逗號或者給sql語句前拼接 where、set以及values(正括號等前綴,或者添加)反括號等后綴,可用於選擇性插入、更新、刪除或者條件查詢等操作;
B. 標簽屬性
屬性 | 描述 |
prefix |
給sql語句拼接的前綴 |
prefixOverrides |
去除sql語句前面的關鍵字或者字符,該關鍵字或者字符由prefixesToOverride屬性指定,假設該屬性指定為AND,當sql語句的開頭為AND,trim標簽將會去除該AND |
suffix |
給sql語句拼接的后綴 |
suffixOverrides |
去除sql語句后面的關鍵字或者字符,該關鍵字或者字符由suffixesToOverride屬性指定 |
C. 示例
<insert id="insertSelective" parameterType="com.ruhuanxingyun.Manufacture" > insert into manufacture <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="productType != null" > product_type, </if> <if test="sdkNum != null" > sdk_num, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=BIGINT}, </if> <if test="productType != null" > #{productType,jdbcType=VARCHAR}, </if> <if test="sdkNum != null" > #{sdkNum,jdbcType=CHAR}, </if> <if test="deviceType != null" > #{deviceType,jdbcType=BIT}, </if> </trim> </insert>
4. where 標簽
A. where標簽只會在至少有一個子元素的條件返回SQL子句的情況下才去插入WHERE子句,若語句的開頭為AND或OR,where元素會將它們自動去除;
B. 可以用trim標簽來處理
<trim prefix="WHERE" prefixOverrides="AND | OR">
...
</trim>
C. 示例
<select id="findAreaInfoListByCode" parameterType="java.lang.String" resultType="com.model.map.AreaInfoTree"> select area_name as title, concat (area_code, '_', ifnull (xpoint, ''), '_', ifnull (ypoint, '')) as `key`, if (xpoint || ypoint, 0, 1) as disabled from area_info <where> p_area_code = #{areaCode} <if test="areaCode == 0"> and area_code != '660000' </if> </where>
</select>
5. set 標簽
A. set標簽會動態前置SET關鍵字,同時也會刪掉無關的逗號;
B. 可以用trim標簽替代
<trim prefix="SET" suffixOverrides=",">
...
</trim>
C. 示例
<update id="updateFactoryInfo" parameterType="com.model.dockingmanager.FactoryInfo"> update factory_info <set> <if test="factoryName!=null and factoryName!='' "> factory_name = #{factoryName}, </if> <if test="wEquipmentFactory!=null and wEquipmentFactory!=''"> w_equipment_factory = #{wEquipmentFactory,jdbcType=INTEGER}, </if> update_time = now() </set> WHERE id = #{id} </update>
6. foreach標簽
A. 應用場景:對集合數據進行遍歷,比如在構建IN條件語句時;
B. 標簽屬性
屬性 | 描述 |
collection |
表示傳遞進來的參數名稱 |
item |
表示循環中當前的元素或鍵值 |
index |
表示當前元素在集合的位置下標(List/Set/Array)或鍵key(Map) |
open/close |
表示以什么符號將這些集合元素包裝起來 |
separator |
表示各個元素的間隔符 |
C. 示例