3、动态标签详解: if、 where、trim、set、 foreach、choose、bind



一、MyBatis 框架 动态标签



       动态标签主要搭配顶级标签使用,实现将映射的 SQL 语句动态化。



1、if 标签


if 标签的作用:动态拼接

       其实和 Java 中的 if 语句是一样的,都是进行判断,符合判断条件的便执行指定内容,否则跳过判断。
  • if 标签的相关属性
    • test 属性: 添加判断条件

XML 代码展示

     <select id="queryIf" parapeterType ="com.modules.dto.User"  resultType ="com.modules.dto.User">
     
            <!-- 因为有 where 就必须有查询条件,如果没有便会报错,所以加上 1=1条件 -->   
    		select id,username,password from user where 1=1
    		
    		    <!-- 判断传入的参数是否为空 -->   
    			<if test="id != null">
    				and id= #{id}
    			</if>
     </select>




2、where 标签


where 标签的作用:去除多余的 where

       当使用 if 标签进行动态 SQL 拼接时,如果 if 标签的判断条件不满足的话,便不拼接 if 标签中的内容,这便导致了 SQL 语句的 where 子句缺失,造成 SQL 错误。
       使用 where 标签便可以解决上述问题,使用 where 标签将 if 标签包裹起来,当 if 标签的判断条件不满足,动态 SQL 不拼接时,便不会向 SQL 语句中插入 where 子句,从而避免该错误。

XML 代码展示

     <select id="queryWhere" parapeterType ="com.modules.dto.User"  resultType ="com.modules.dto.User">
    		select id,name.paw from user 
    		  <where >
    			<if test="id != null">
    				and id= #{id}
    			</if>
    		  </where >
     </select>




3、set 标签


set 标签的作用:去除多余逗号

       当我们去编写动态修改 SQL 语句时,会使用 if 标签去动态拼接修改的内容,并且动态拼接的修改条件通常都会有 “,” 的存在,但是因为是动态拼接无法保证那一条拼接的修改条件是最后一条,这就导致了拼接完成后可能存在多余的 “,” ,造成 SQL 错误。
       使用 set 标签将这些动态拼接修改的内容的 if 标签包裹起来,便可以去除多余的 “,” 。

XML 代码展示

	<update id="updateById" parameterType="com.demo_01.entity.User">
 	        update user 
     	        <set>
     	        	<if test="name != null">
   						username = #{username},
   					</if>
   					<if test="name != null">
   						password = #{password},
   					</if>
   					<if test="name != null">
   						age=#{age},
   					</if>
     	        </set>
 	          <where >
    			<if test="id != null">
    				and id= #{id}
    			</if>
    		  </where >
 	 </update>




4、trim 标签


trim 标签的作用:动态拼接时去除 SQL 的前缀、后缀,或者拼接前缀后缀

  • trim 标签的相关属性

    • prefix 属性: 拼接前缀

    • suffix 属性: 拼接后缀

    • prefixOverrides 属性: 去除前缀

    • suffixOverrides 属性: 去除后缀


XML 代码展示

   <select id="count" result="java.lang.Integer">
   	select count(*) from user
   	<trim prefix ="where" prefixOverrides="and | or">
   		<if test="id != null">id = #{id}</if>
   		<if test="username != null"> and username = #{username}</if>
   	</trim>
   </select>
  • 如果 id 或者 username 有一个不为空,则在语句前加入 where。如果 where 后面紧随 and 或 or 就会自动会去除

  • 如果 id 或者 username 都为空,则不拼接任何东西




5、foreach 标签


foreach 标签的作用:相当于 Java 中的 for 循环,将结果动态获取到 SQL 当中。

  • foreach 标签的相关属性

    • collection 属性: 用来指定循环遍历的参数类型,如果参数类型为 List,则该值为 list。如果参数类型为数组,则该值为 array。

    • item 属性: 循环的key(可以自定义 key 值),如果传入的集合是实体类类型的,可以通过 key.集合中的属性来获取数据,如果就是普通的 add 存储就直接遍历 key 即可

    • index 属性: 循环的下标顺序

    • open 属性: 指定循环开始的内容

    • close 属性: 指定循环结束的内容

    • separator 属性: 指定循环在每次迭代时所使用的分隔符(根据需求自定义使用什么)

XML 代码展示

   <select id="count" resultType="java.lang.Integer">
   	select count(*) from user where id in
     	<foreach collection="list" item="i" index="index" open="(" separator="," close=")">
           #{i.id}
     	</foreach>
   </select>




5.1、foreach 标签扩展 Oracle and MySQL 批量插入

XML 代码展示

   <sql id="base_column">id, question_id, answer</sql>
   
   <!-- oracle的批量插入 -->
   <insert id="insertBatchOracle" parameterType="list">
       insert into question_answer ( <include refid="base_column" /> ) 
       select question_answer_seq.NEXTVAL, A.* from (
           <foreach collection="list" item="item" separator="union all">
               select #{item.questionId}, #{item.answer} from dual
           </foreach>
       ) A 
   </insert>
   
   <!-- Mysql的批量插入,主键自增 -->
   <insert id="insertBatchMysql" parameterType="list">
       insert into question_answer ( <include refid="base_column" /> ) 
       values 
           <foreach collection="list" item="item" open="(" separator="union all" close=")">
               #{item.id}, #{item.questionId}, #{item.answer}
           </foreach>
   </insert>




6、choose 标签


choose 标签的作用:去除多余条件

       在使用 if 标签编写需要判断的条件时,如果表达式内容的判断结果为 true 那么条件就满足。当有多个条件满足,并且实际业务并不需要这么多的条件或者只需要一个条件时便可以使用此标签去除条件。

       choose 标签是按顺序判断其内部 when 标签中的 test 条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的 sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

XML 代码展示

 <select id="queryChoose" parapeterType ="com.modules.dto.User"  resultType ="com.modules.dto.User">        select * from user where 1 = 1 
        <choose>
            <when test="id != null">
                and id = #{id}
            </when>
            <when test="name != null">
                and name = #{name}
            </when>
            <otherwise>
                and paw = "123456"
            </otherwise>
        </choose>
    </select>




7、bind 标签


bind 标签的作用:对数据进行再次加工,预防 SQL 注入,模糊查询

       bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。

XML 代码展示

<select id="count" resultType="java.lang.Integer">
	select count(*) from user
	<where>
		<if test="name != null">
			<bind name="username" value="'%' + username + '%'"/>
			name like #{username}
		</if>
</select>




  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
trim标签是一个通用标签,可以用于set或where等场景。它有几个属性,包括prefix(前缀关键字)、suffix(后缀关键字)、prefixOverrides(忽略前置字符)和suffixOverrides(忽略后置字符)。prefix属性表示要附加的前缀关键字,suffix属性表示要附加的后缀关键字,prefixOverrides属性表示要忽略前置字符,suffixOverrides属性表示要忽略后置字符。 在SQL中,TRIM函数是用于移除字符串中的指定字符或空白。它有三个参数,分别是位置(LEADING、TRAILING或BOTH)、要移除的字串和待处理的字符串。如果不指定要移除的字串,则默认会移除空白。 trim标签在应用中有多种用法。在where语句中,可以使用trim标签动态生成条件语句。在set标签中,可以使用trim标签动态生成更新语句。trim标签还可以与if标签foreach标签等结合使用,实现更复杂的逻辑。 下面是几个使用trim标签的示例: 1. 用于where语句: <select id="getUserDy01" parameterType="map" resultType="user"> select * from user <trim prefix="where" prefixOverrides="and"> <if test="uname!=null and uname!=''"> and uname like '%${uname}%' </if> <if test="sex!=null and sex!=''"> and sex=#{sex} </if> </trim> </select> 2. 用于set标签: <update id="updateUserById" parameterType="user"> update user <trim prefix="set" suffixOverrides="," suffix="where uid=#{uid}"> <if test="uid!=null"> uid=#{uid}, </if> <if test="uname!=null and uname!=''"> uname=#{uname}, </if> <if test="sex!=null and sex!=''"> sex=#{sex}, </if> <if test="password!=null and password!=''"> password=#{password}, </if> <if test="birthday!=null"> birthday=#{birthday} </if> </trim> </update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值