动态SQL

1. if

根据条件添加或不添加sql语句,一般判断是否传递参数

<!--通过用户名或者id查询用户-->
    <select id="getUserByUserCodeOrId" parameterType="map" resultType="User">
        select * from smbms_user where id = #{id}
        <if test="userCode != null">
            and userCode = #{userCode}
        </if>
    </select>

注意:test中的变量名不需要加#{}

2. choose、when、otherwise

根据条件从多个sql语句中选择一个

<select id="getUserByUserCodeOrId" parameterType="map" resultType="User">
    select * from smbms_user
    <where>
        <choose>
            <when test="id != null">
                id = #{id}
            </when>
            <when test="userCode != null">
                userCode = #{userCode}
            </when>
            <otherwise>
                userName = #{userName}
            </otherwise>
        </choose>
    </where>
</select>

3. trim、where、set

3.1 where

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

3.2 set

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

3.3 trim

  1. 覆盖了前缀值设置,并且自定义了前缀值

    <trim prefix="WHERE" prefixOverrides="AND |OR ">
      ...
    </trim>
    
  2. 覆盖了后缀值设置,并且自定义了前缀值

    <trim prefix="SET" suffixOverrides=",">
      ...
    </trim>
    

4. foreach

  • 对集合进行遍历(尤其是在构建 IN 条件语句的时候)
  • 可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值