MyBatis - 常用标签与动态Sql

MyBatis常用标签

● 定义sql语句:select、insert、delete、update
● 配置JAVA对象属性与查询结构及中列明对应的关系:resultMap
● 控制动态sql拼接:if、foreach、choose
● 格式化输出:where、set、trim
● 配置关联关系:collection、association
● 定义常量及引用:sql、include

MyBatis提供了对SQL语句动态的组装能力,大量的判断都可以在 MyBatis的映射XML文件里面配置,以达到许多我们需要大量代码才能实现的功能,大大减少了我们编写代码的工作量。

动态SQL的元素

在这里插入图片描述

一、定义sql标签

● select标签

  • id:唯一的标识符

  • parameterType:传给此语句的参数的全路径名或别名 例:com.sikiedu.beans.User 或 user

  • resultType:语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap 不能并用)

<select id="selectUserById" parameterType="User" resultType="User">
    SELECT * FROM user WHERE id = #{id}
</select>

● insert标签

  • id:唯一的标识符

  • parameterType:传给此语句的参数的全路径名或别名 例:com.sikiedu.beans.User


<insert id="insertUser" parameterType="com.sikiedu.beans.User">
   INSERT INTO user VALUES(null,#{username},#{userpassword},#{balance},#{grgisterdate})
</insert>

● delete标签

  • 属性同 insert
<delete id="deleteUserById" parameterType="Integer">
    DELETE FROM user WHERE id = #{id}
</delete>

● update标签

  • 属性同 insert
<update id="updateUser" parameterType="com.sikiedu.beans.User">
    UPDATE user SET username = #{username} WHERE id = #{id}
</update>

二、动态 sql 拼接

● if标签 - if 标签通常用于 WHERE 语句、UPDATE 语句、INSERT 语句中。

通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。

<select id="selectRoleListByRole" parameterType="Role" resultMap="roleResultMap">
    SELECT * FROM user
    <where>
        <if test="level!=null and level!=''">
            level = #{level}
        </if>
        <if test="roletype!=null and roletype!=''">
            AND roletype = #{roletype}
        </if>
        <if test="userid!=null">
            AND userid = #{userid}
        </if>
    </where>
</select>

● foreach标签 -主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。

  • collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。

  • item:表示在迭代过程中每一个元素的别名

  • index:表示在迭代过程中每次迭代到的位置(下标)

  • open:前缀

  • close:后缀

  • separator:分隔符,表示迭代时每个元素之间以什么分隔

<select id="selectRoleListByids" resultMap="roleResultMap">
    SELECT * FROM user
    WHERE idrole IN
    <foreach collection="array" item="id" open="(" separator="," close=")">
        ${id}
    </foreach>
</select>

● choose标签 - 类似于 Java 的 switch 语句

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis 提供了 choose 元素,按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。

当 choose 中所有 when的条件都不满则时,则执行 otherwise 中的 sql。类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default

<select id="getRoleListChoose" parameterType="Role" resultMap="roleResultMap">
    SELECT * FROM role
    <where>
        <choose>
            <when test="name!=null and name!='' ">
                AND name LIKE "%"#{name}"%"
            </when>
            <when test="userid!= null">
                AND userid = #{userid}
            </when>
            <otherwise>
                AND roletype = "射手"
            </otherwise>
        </choose>
    </where>
</select>

三、格式化输出

● where标签 - 解决if标签拼接字符串AND符号问题

当 if 标签较多时,这样的组合可能会导致错误。 如下:

<select id="getRoleListWhere" parameterType="Role" resultMap="roleResultMap">
    SELECT * FROM role WHERE
    <if test="name!=null and name!=' ' ">
        name = #{name}
    </if>
    <if test="roletype!=null and roletype!=' ' ">
        AND roletype = #{roletype}
    </if>
    <if test="userid!=null">
        AND userid = #{userid}
    </if>
</select>

当 name 值为 null 时,查询语句会出现 “WHERE AND” 的情况,解决该情况除了将"WHERE"改为“WHERE 1=1”之外,还可以利用 where标签。

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

<select id="selectRoleListByRole" parameterType="Role" resultMap="roleResultMap">
    <include refid="myselect"></include>
    <where>
        <if test="name!=null and name!=''">
            name = #{name}
        </if>
        <if test="roletype!=null and roletype!=''">
            AND roletype = #{roletype}
        </if>
        <if test="userid!=null">
            AND userid = #{userid}
        </if>
    </where>
</select>

● set标签 - 解决更新数据表时字符串拼接逗号”,”问题;

没有使用 if 标签时,如果有一个参数为 null,都会导致错误。

当在 update 语句中使用 if 标签时,如果最后的 if 没有执行,则或导致逗号多余错误。

使用 set 标签可以将动态的配置 set 关键字,和剔除追加到条件末尾的任何不相关的逗号。

<update id="updateSetRole" parameterType="Role">
    UPDATE role
    SET name = '${name}',
    level = ${level},
    roletype = '${roletype}',
    userid = ${userid}
    WHERE idrole = #{id}
</update>

<update id="updateSetRole" parameterType="Role">
    UPDATE role SET
    <if test="name != null and name != ''">
        name = '${name}',
    </if>
    <if test="level != null">
        level = ${level},
    </if>
    <if test="roletype != null and roletype != ''">
        roletype = '${roletype}',
    </if>
    <if test="userid != null">
        userid = ${userid}
    </if>
    WHERE idrole = #{id}
</update>

使用 set+if 标签修改后,如果某项为 null 则不进行更新,而是保持数据库原值。

<update id="updateSetRole" parameterType="Role">
    UPDATE role
    <set>
        <if test="name != null and name != ''">
            name = '${name}',
        </if>
        <if test="level != null">
            level = ${level},
        </if>
        <if test="roletype != null and roletype != ''">
            roletype = '${roletype}',
        </if>
        <if test="userid != null">
            userid = ${userid}
        </if>
    </set>
    WHERE idrole = #{id}
</update>

● trim标签 - trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能

  • prefix:在trim标签内sql语句加上前缀

  • suffix:在trim标签内sql语句加上后缀

  • prefixOverrides:指定去除多余的前缀内容,如:prefixOverrides=“AND | OR”,去除trim标签内sql语句多余的前缀"and"或者"or"。

  • suffixOverrides:指定去除多余的后缀内容。

<select id="selectRoleListByTrim" parameterType="Role" resultMap="roleResultMap">
    SELECT * FROM role
    <trim prefix="WHERE" suffixOverrides="AND">
        <if test="name!=null and name!=''">
            name = #{name} AND
        </if>
        <if test="roletype!=null and roletype!=''">
            roletype = #{roletype} AND
        </if>
        <if test="userid!=null">
            userid = #{userid} AND
        </if>
    </trim>
</select>

如果name、roletype和userid的值都不为空的话,会执行如下语句

SELECT * FROM role WHERE name = #{name} AND roletype = #{roletype} AND userid = #{userid}

会为片段添加 “WHERE” 前缀,并忽略最后个 “and”

四、定义常量及引用

● sql标签 – 可以提取重复sql语句片段;

当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求 结构清晰也可将 sql 语句分解。

<sql id="myselect">
    SELECT * FROM role
</sql>

● include - 用于引用定义的常量

<resultMap type="Role" id="roleRM">
    <id property="id" column="idrole" />
</resultMap>
<select id="selectAllRole" resultMap="roleRM">
    <include refid="myselect"></include>
</select>

<select id="selectRoleListByids" resultMap="roleRM">
    <include refid="myselect"></include>
    WHERE idrole IN
    <foreach collection="array" item="id" open="(" separator="," close=")">
        ${id}
    </foreach>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值