【mybatis学习】--mapper.xml中常用的标签积累

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/YYZZHC999/article/details/82319305

一· 常用标签组示例:

二、部分标签总结

1.sql片段标签<sql>:


通过该标签可定义能复用的sql语句片段,在执行sql语句标签中直接引用即可。这样既可以提高编码效率,还能有效简化代码,提高可读性,  需要配置的属性:id="" >>>表示需要改sql语句片段的唯一标识
 引用:通过<include refid="" />标签引用,refid="" 中的值指向需要引用的<sql>中的id=“”属性  

<!--定义sql片段-->
   <sql id="orderAndItem">
          o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count
      </sql>
     
     <select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">
         select
    <!--引用sql片段-->
          <include refid="orderAndItem" />
          from ordertable o
         join orderitem i on o.orderitem_id = i.orderitem_id
         where o.order_id = #{orderId}
     </select>


下面是一些常用的动态语句标签:通过动态sql标签可以进行条件判断,条件遍历等操作从而满足结果的需要

2. <where> 标签:

使用其可以代替sql语句中的where关键字,一般防止在条件查询的最外层
 

3. <set> 标签:

与where标签类似 常用于<update>更新语句中,替代 sql中的“set”关键字,特别是在联合<if>进行判断是,可以有效方式当某个参数为空或者不合法是错误的更新到数据库中


4. <if > 标签:

条件判断标签,配置属性test=" 条件字符串 ",判断是否满足条件,满足则执行,不满足则跳过

    <select id="findOrderItemDetail" parameterType="pojo.Orderitem" resultMap="BaseResultMap">
              select orderitem.orderitem_id,product.* 
              from orderitem,product
              <where>
                  <if test="orderitemId!=null and orderitemId!=''">
                      and orderitem.orderitem_id = #{orderitemId}
                  </if>
                  <if test="productId!=null and productId!=''">
                      and orderitem.product_id = #{productId}
                  </if>
                  <if test="count!=null">
                      and orderitem.count = #{count}
                  </if>
              </where>
     </select>

5.<choose></choose>标签组:

完整标签结构如下:

<choose>

<when></when> 
<when></when>

<otherwise></otherwise>
</choose>


choose标签组也是一个用于条件判断的标签组,和<if>的不同之处在于条件从<choose>进入,去匹配<when>中的添加,一旦匹配马上结束;若到找不到匹配项,将执行<other>中的语句;可以理解为<if>是 && 关系 <choose>是 || 关系,中间的<when></when>可以根据情况添加多组,执行效果类似swich case。

6. <foreach>标签:

该标签的作用是遍历集合类型的条件 ,类似与Angular中的*ngFor指令
  属性:collection=“array” / collection = “list”  ----->是数组类型,还是集合类型     item=“ productId ”------> 参数名
      open="(" separator="," close=")"  ------>开始符号,分隔符号,结束符号 
      index=“ ” ---->结束下标位置,不配置该参数时,默认为全部遍历

     <delete id="deleteByPriKeys" parameterType="java.lang.String">
           delete from product where product_Id in
           <foreach collection="list" item="productId" open="(" separator="," close=")">
                #{productId,jdbcType = VARCHAR}
           </foreach>
      </delete> 


 

猜你喜欢

转载自blog.csdn.net/YYZZHC999/article/details/82319305