MyBatis常用标签

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

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

动态SQL的元素

元素 作用 备注
if 判断语句 单条件分支判断
choose、when、otherwise 相当于 Java 中的 switch case default 语句 多条件分支判断
trim、where、set 辅助元素 用于处理一些 SQL 拼装问题
foreach 循环语句 在in语句等列举条件常用

一、定义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语句片段;

当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求 <select> 结构清晰也可将 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>

MyBatis - 常用标签与动态Sql的更多相关文章

  1. MyBatis学习总结_11_MyBatis动态Sql语句

    MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...

  2. SSM框架之Mybatis(6)动态SQL

    Mybatis(6)动态SQL 1.动态SQL 出现原因:有些时候业务逻辑复杂时,我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了 1.1.if标签 我们根据实体类的不 ...

  3. Spring mybatis源码篇章-动态SQL节点源码深入

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-动态SQL基础语法以及原理 前话 前文描述到通过mybatis默认的解析驱动类org.apache.ibat ...

  4. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)——动态SQL

  5. Mybatis学习笔记之---动态sql中标签的使用

    动态Sql语句中标签的使用 (一)常用标签 1.<if> if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段 ...

  6. Mybatis系列全解(八):Mybatis的9大动态SQL标签你知道几个?提前致女神!

    封面:洛小汐 作者:潘潘 2021年,仰望天空,脚踏实地. 这算是春节后首篇 Mybatis 文了~ 跨了个年感觉写了有半个世纪 ... 借着女神节 ヾ(◍°∇°◍)ノ゙ 提前祝男神女神们越靓越富越嗨 ...

  7. Mybatis 常用标签

    MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...

  8. [Mybatis]Mybatis 常用标签及功能整理

    Mybatis中生成动态SQL的标签有四类,分别是: if choose (when, otherwise) trim (where, set) foreach 1.if 当需要动态生成where条件 ...

  9. mybatis常用标签

    1. 定义sql语句 1.1 select 标签 属性介绍: id :唯一的标识符. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user ...

随机推荐

  1. leetcood学习笔记-107-二叉树的层次遍历二

    题目描述: 方法一: class Solution(object): def levelOrderBottom(self, root): """ :type root: ...

  2. C++11的闭包(lambda、function、bind)

    c++11开始支持闭包,闭包:与函数A调用函数B相比较,闭包中函数A调用函数B,可以不通过函数A给函数B传递函数参数,而使函数B可以访问函数A的上下文环境才可见(函数A可直接访问到)的变量:比如: 函 ...

  3. NX二次开发-获取UG界面窗口句柄UF_UI_get_default_parent

    1 extern "C" DllExport void ufusr(char *param, int *retcod, int param_len) 2 { 3 4 if (UF_ ...

  4. [JZOJ 5861] 失意

    思路: 求交集最大老套路,排序之后用堆维护即可. #include <bits/stdc++.h> using namespace std; const int mod = 1e9+7; ...

  5. python3 线程 threading.Thread GIL性能详解(2.3)

    python3 线程 threading 最基础的线程的使用 import threading, time value = 0 lock = threading.Lock() def change(n ...

  6. 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 转载 https://www.cnblogs.com/yunfeifei/p/3993401.html

    5天玩转C#并行和多线程编程系列文章目录 5天玩转C#并行和多线程编程 —— 第一天 认识Parallel 5天玩转C#并行和多线程编程 —— 第二天 并行集合和PLinq 5天玩转C#并行和多线程编 ...

  7. A1075 PAT Judge (25 分)

    The ranklist of PAT is generated from the status list, which shows the scores of the submissions. Th ...

  8. Python3 From Zero——{最初的意识:007~函数}

    一.编写可接受任意数量参数的函数:*.** >>> def test(x, *args, y, **kwargs): ... pass ... >>> test(1 ...

  9. servlet的xml配置详解

    <?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns ...

  10. 转:手机端html5触屏事件(touch事件)

    touchstart:触摸开始的时候触发 touchmove:手指在屏幕上滑动的时候触发 touchend:触摸结束的时候触发 而每个触摸事件都包括了三个触摸列表,每个列表里包含了对应的一系列触摸点( ...