MyBatis中的常见的标签(resultMap)sql where if标签 set标签 trim标签 foreach标签

MyBatis中的标签

1.resultMap

完成实体类和数据表的映射
<resultMap id="唯一表示" type="声明映射的对象">
<id property="对象中的主键属性" cloum="表中的主键">
<result property="对象中的主键属性" cloum="表中的对应字段">
</resultMap>

2.sql标签

能够提取sql语句中的公共部分使用 <include refid="sql标签的id"/>

<!--抽取公共的sql片段-->
    <sql id="baseUser">
        id,
        name,
        password,
        role_name
    </sql>
<select id="getUserList" resultMap="userResultMap">
    select
     <include refid="baseUser"/>
     from t_user;
</select>

3.where标签

能够给sql语句自动添加一个where,而且能够去掉sql中多余的and

if标签

判断传入的参数值是否为空或者为空字符串,达到根据不同的条件查询不同数据的目的

<select id="findUserList" resultMap="userResultMap">
        select
        <include refid="baseUser"/>
        from t_user
        <where>
            <if test="name != null and name != ''">
                and name like concat("%",#{name},"%")
            </if>
            <if test="password != null and password !=''">
                and password=#{password}
            </if>
        </where>

    </select>

4.set标签

为sql语句添加一个set,并且能够去掉末尾多余的,

 <update id="updateUser">
        update t_user
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
        </set>
        where id=#{id}
    </update>

5.trim标签

可以代替where标签和set标签

  <update id="updateUser1">
        update t_user
        <!--
       prefix:前缀在语句之前添加内容
       suffix:后缀在语句之后添加的内容
       suffixOverrides:后缀覆盖,去除后面多余的,
       prefixOverrides:前缀覆盖,去除前面多余的and
        -->
      <trim prefix="set" suffix="" prefixOverrides="" suffixOverrides=",">
          <if test="name != null and name != ''">
              name = #{name},
          </if>
          <if test="password != null and password != ''">
              password = #{password},
          </if>
      </trim>
           where id=#{id}
    </update>

6.foreach标签

用户批量删除,循环遍历list

    <delete id="batchDel">
        DELETE from t_user where id  in
        <!--
        collection:遍历的集合
        open:开始遍历是调用
        close:结束时调用
        item:当前遍历的对象
        separator:每次遍历都执行
        index:当前遍历的索引值
        -->
        <foreach collection="list" open="(" close=")" item="id" separator="," index="index">
        #{id}
        </foreach>
    </delete>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值