Mybatis 动态SQL怎么写?

一.Mybatis 极简入门

二.Mybatis 级联查询

三.Mybatis 延迟加载

四.Mybatis 缓存策略

本篇:Mybatis 动态SQL

首先来了解一下动态SQL的优点,它可以帮助码农们减少不必要的重复代码,降低工作量。

1. if 标签

if标签用来判断条件是否成立,如果条件成立就执行里面的内容,举个例子:

<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
     select * from student
        <if test="id!=0">
        <!--如果id!=0,则会添加id=#{id}这个条件-->
          id=#{id}
        </if>
         <!--如果name!=null,则会添加name=#{name}这个条件-->
        <if test="name!=null">
          and name=#{name}
        </if>
    </select>

2. where标签

结合if标签使用,能够自动删除and

  <select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
    select * from student
    <where>
        <if test="id!=0">
          id=#{id}
         </if>
        <if test="name!=null">
         and name=#{name}
        </if>
    </where>
    </select>

看上面的代码,如果id没有设置,那么语句会变成 select * from where and name=#{name}
但是我们有where标签就能够将这个 and删除
在这里插入图片描述

3. choose标签

 <select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
        select * from student
        <where>
           <choose>
           <!--如果一个条件成立,立马结束,多个选择一个-->
               <when test="id!=0">
                   and id=#{id}
               </when>
               <when test="name!=null">
                  and name=#{name}
               </when>
           </choose>
        </where>
    </select>

4. trim标签

<select id="findStudentByAll" parameterType="com.ibuyi.mybatis.entity.Student" resultType="com.ibuyi.mybatis.entity.Student">
        select * from student
        <trim prefix="where" prefixOverrides="and">
            <if test="id!=0">
                and id=#{id}
            </if>
            <if test="name!=null">
                and name=#{name}
            </if>
        </trim>
    </select>

prefix和prefixOverrides不能在一起,如果在一起就把后面的删除掉。

5.Set标签

当我们想更新某个多字段表时,只有一个字段改动,其他字段无需要更改,但是这个字段并不确定,传统的sql做法就是写很多update语句,但是set标签给我们提供了更方便的方法。

<update id="findStudentByAll">
        update student
       <!--只有不为空,才会执行set操作,也不需要重复写多条sql语句了-->
        <set>
            <if test="id!=0">
                id=#{id}
            </if>
            <if test="name!=null">
                name=#{name}
            </if>
        </set>
        where id=#{id}
    </update>

猜你喜欢

转载自blog.csdn.net/weixin_43927892/article/details/104536917