Mybatis动态SQL标签

需求分析

在运用框架之前,通过jdbc连接方式,将dao层的连接数据库方法化,而在实际开发中,通过不同的条件查询得到相同数据结构的方法,我们通常通过判断/赋值等方法将众多的查询合并成一个方法。
在mybatis框架中,通过sql直接查询数据库,在具有类似的查询中,也有相类似的方法将多条类似的sql合并或拼接。

if

用法:

<select id="select" resultType="Student">
  SELECT * FROM student 
  WHERE id < #{id}
  <if test="name != null">
    AND name like '%'#{title}'%'
  </if>
</select>

这条语句提供了一种可选的查找文本功能。如果没有传入“name”,那么所有处于“id<#{id}”都会返回;反之若传入了“name”,那么就会对查询结果再进行“name”进行模糊查找并返回 结果。

choose/when/otherwise

MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
      select * from user
      <where>
          <choose>
              <when test="id !='' and id != null">
                  id=#{id}
              </when>
              <when test="username !='' and username != null">
                  and username=#{username}
              </when>
              <otherwise>
                  and sex=#{sex}
              </otherwise>
          </choose
      </where>
  </select>

这里我们有三个条件,id,username,sex,只能选择一个作为查询条件
    如果 id 不为空,那么查询语句为:select * from user where id=?
    如果 id 为空,那么看username 是否为空,如果不为空,那么语句为 select * from user where username=?;
    如果 username 为空,那么查询语句为 select * from user where sex=?

if/where
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <where>
        <if test="username != null">
           username=#{username}
        </if>       
        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>
</select>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

if/set
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
    update user u
        <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set>
     where id=#{id}
</update>

这样写,如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?

如果第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值