首页 > 数据库 >【Mybatis】动态SQL

【Mybatis】动态SQL

时间:2022-08-17 22:36:09浏览次数:71  
标签:username 语句 user SQL Mybatis 动态 where id

目录

    1. 动态SQL if语句
    1. 动态SQL if+where语句
    1. 动态SQL if+set语句
    1. 动态SQL choose(when,otherwise)语句
    1. 动态SQL trim语句
    1. 动态SQL SQL片段
    1. 动态SQL foreach语句

动态SQL if语句

<select id="selectUserByUsernameAndAge" resultMap="UserMap">
    select * from user where
    <if test="username != null">
        username=#{username}
    </if>

    <if test="age != null">
        and age=#{age}
    </if>
</select>

如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and age=#{age},这是错误的 SQL 语句

动态SQL if+where语句

<select id="selectUserByUsernameAndAge" resultMap="UserMap">
    select * from user
    <where>
        <if test="username != null">
            username=#{username}
        </if>
    
        <if test="age != null">
            and age=#{age}
        </if>
    </where>
</select>

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

动态SQL if+set语句


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

动态SQL choose(when,otherwise)语句

<select id="selectUserByChoose" resultType="com.kdgc.wx.entity.User" parameterType="com.kdgc.wx.entity.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 age=#{age}
              </otherwise>
          </choose>
      </where>
  </select>

动态SQL trim语句

trim标记是一个格式化的标记,可以完成set或者是where标记的功能

①、用 trim 改写上面第二点的 if+where 语句

<select id="selectUserByUsernameAndAge" resultType="user" parameterType="com.kdgc.wx.entity.User">
        select * from user
    <!-- <where>
          <if test="username != null">
             username=#{username}
          </if>
           
          <if test="username != null">
             and sex=#{sex}
          </if>
      </where>  -->
        <trim prefix="where" prefixOverrides="and | or">
            <if test="username != null">
               and username=#{username}
            </if>
            <if test="sex != null">
               and sex=#{sex}
            </if>
        </trim>
    </select>

prefix:前缀
prefixoverride:去掉第一个and或者是or

②、用 trim 改写上面第三点的 if+set 语句

<!-- 根据 id 更新 user 表的数据 -->
    <update id="updateUserById" parameterType="com.kdgc.wx.entity.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> -->
            <trim prefix="set" suffixOverrides=",">
                <if test="username != null and username != ''">
                    u.username = #{username},
                </if>
                <if test="sex != null and sex != ''">
                    u.age = #{age},
                </if>
            </trim>
         
         where id=#{id}
    </update>

suffix:后缀
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

动态SQL SQL片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

<!-- 定义 sql 片段 -->
<sql id="selectUserByUserNameAndAgeSQL">
    <if test="username != null and username != ''">
        AND username = #{username}
    </if>
    <if test="age != null and age != ''">
        AND age = #{age}
    </if>
</sql>

引用 sql 片段

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.kdgc.wx.entity.User">
    select * from user
    <trim prefix="where" prefixOverrides="and | or">
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="selectUserByUserNameAndSexSQL"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </trim>
</select>

注意:
①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②、在 sql 片段中最好不要包括 where

动态SQL foreach语句

需求:我们需要查询 user 表中 id 分别为1,2,3的用户

sql语句:
select * from user where id=1 or id=2 or id=3
select * from user where id in (1,2,3)

  • foreach 来改写 select * from user where id=1 or id=2 or id=3
<select id="selectUserByListId" parameterType="com.kdgc.wx.entity.UserVo" resultType="com.kdgc.wx.entity.User">
    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and (id=1 or id=2 or id=3)
          -->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

  • foreach 来改写 select * from user where id in (1,2,3)
<select id="selectUserByListId" parameterType="com.kdgc.wx.entity.UserVo" resultType="com.kdgc.wx.entity.User">
    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and id in (1,2,3)
          -->
        <foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
            #{id}
        </foreach>
    </where>
</select>

文章参考:https://www.cnblogs.com/ysocean/p/7289529.html

标签:username,语句,user,SQL,Mybatis,动态,where,id
From: https://www.cnblogs.com/HelloWxl/p/16597008.html

相关文章

  • MySQL查询关键数据方法
    MySQL查询关键数据方法操作表的SQL语句补充1.修改表名 altertable表名reame新表名;2.新增字段名 altertable表名add字段名字段类型(数字)约束条件;#默认队尾......
  • SQLMAP系列强化
    案例1:DC-9图1:尝试‘or1=1--+    //判断存在注入kali中使用sqlmap工具跑就完了sqlmap-u"http://192.168.178.135/results.php"--data"search=1" ......
  • 20220817 第一组 于芮 mysql数据库查询(第三十四天)
     小白成长记——第三十四天   今天主要学习了mysql数据库的查询语句,对于一个合格的程序猿来说,掌握数据库的查询语句是非常重要的,所以今天不仅学习了理论知识,还作了......
  • MySQL之表查询关键字
    操作表的SQL语句补充修改表名创建一张表:createtableaa(idintprimarykeyauto_increment);altertable表名rename新表名;altertableaarenameabb;新增字......
  • MySQL查询关键字where、group by、having、distinct、order by、limit、redexp正则、
    目录操作表的SQL语句补充truncate\delete\drop的区别查询关键字之select与from查询关键字之where筛选查询关键字之groupby分组查询关键字之having过滤查询关键字之distin......
  • MySQL之查询关键字
    今日内容操作表的SQL语句补充1.修改表名 altertable表名remane新表名;2.新增字段 altertable表名add字段名字段类型(数字)约束条件; altertable表名add......
  • mybatispluys-Mapper CRUD 接口
    MapperCRUD接口通用CRUD封装BaseMapper(opensnewwindow)接口,为Mybatis-Plus启动时自动解析实体表关系映射转换为Mybatis内部对象注入容器Insert//插入一条......
  • Mysql使用实际01---SQL分组查询
    1.SQL分组查询使用场景对记录的分组是通过关键字GROUPBY实现的,GROUPBY后面跟着一个定义组的构成的属性列表。 如果我们使用语句GROUPBYA1,……,Ak我们就把记......
  • 批量插入时 java.sql.SQLSyntaxErrorException
    使用shardingspherebatchInsert批量插入时,单次插入300多条数据 ###Errorupdatingdatabase.Cause:java.sql.SQLSyntaxErrorException:Youhaveanerrorinyou......
  • zk学习案例_服务器动态上下线
    前言我的电脑内存只有8G,搭建的集群虚拟机配置如下,本案例也是可以跑的,学习视频为尚硅谷的Zookeeper教程:https://www.bilibili.com/video/BV1to4y1C7gw?p=1&vd_source=c85b......