一文彻底搞懂Mybatis系列(九)之Mybatis动态SQL标签总结

简介: 一文彻底搞懂Mybatis系列(九)之Mybatis动态SQL标签总结

一、if标签

1.if标签中test属性是必须的。

2.if标签中test属性的值是false或者true。

3.如果test是true,则if标签中的sql语句就会拼接。反之,则不会拼接。

4.test属性中可以使用的是:

当使用了@Param注解,那么test中要出现的是@Param注解指定的参数名。@Param(“brand”),那么这里只能使用brand当没有使用@Param注解,那么test中要出现的是:param1 param2 param3 arg0 arg1 arg2…当使用了POJO,那么test中出现的是POJO类的属性名。

5.在mybatis的动态SQL当中,不能使用&&,只能使用and。

<select id="selectList" resultType="Student">
  select * from t_car where 1 = 1
  <if test="guidePrice != null and guidePrice !=''">
    and guide_price > #{guidePrice}
    </if>
  <if test="carType != null and carType != ''">
    and car_type = #{carType}
  </if>
</select>

二、where标签

  • where标签的作用:让where子句更加动态智能。
  • 所有条件都为空时,where标签保证不会生成where子句。·自动去除某些条件前面多余的and或or。
<select id="selectList" resultType="Student">
  select * from t_car
  <where>
    <if test="guidePrice != null and guidePrice !=''">
      and guide_price > #{guidePrice}
      </if>
    <if test="carType != null and carType != ''">
      and car_type = #{carType}
    </if>
  </where>
</select>
  • 如果把and放在后面,如下面代码,这样是不可以的哦
<select id="selectList" resultType="Student">
  select * from t_car
  <where>
    <if test="guidePrice != null and guidePrice !=''">
      guide_price > #{guidePrice} and 
      </if>
    <if test="carType != null and carType != ''">
      car_type = #{carType}
    </if>
  </where>
</select>

三、trim标签

trim标签的属性:

  • prefix:在trim标签中的语句前添加内容·
  • suffix:在trim标签中的语句后添加内容
  • prefixOverrides:前缀覆盖掉(去掉)
  • suffixOverrides:后缀覆盖掉(去掉)

案例如下:

<select id="selectByMultiConditionWithTrim" resultType="Car">
        select * from t_car
        <!--
            prefix:加前缀 suffix:加后缀
            prefix0verrides:删除前缀 suffix0verrides:删除后缀
            prefix="where"是在trim标签所有内容的前面添加 where
        -->
        <!--
            suffix0verrides="and|or"把trim标签中内容的后缀and或or去掉
        -->
        <trim prefix="where" suffixOverrides="and|or">
            <if test="brand != null and brand != ''">
                brand like "%"#{brand}"%" and</if>
            <if test="guidePrice != null and guidePrice != ''">
                guide price > #{guideprice} and</if>
            <if test="carType != null and carType != ''">
                car_type = #{carType}</if>
        </trim>
    </select>

案例说明:

prefix:加前缀 suffix:加后缀

prefix0verrides:删除前缀 suffix0verrides:删除后缀

prefix="where"是在trim标签所有内容的前面添加 where

suffix0verrides="and|or"把trim标签中内容的后缀and或or去掉

四、set标签

  • 主要使用在update语句当中,用来生成set关键字,同时去掉最后多余的“,”
  • 比如我们只更新提交的不为空的字段,如果提交的数据是空或者"",那么这个字段我们将不更新。

传统写法:

<update id="update">
        update t_car set
            name = #{name},
            sex = #{sex}
        where id = #{id}
    </update>

如果需要避免更新空值字段,可以这样写,并且可以自动的去掉最后的逗号

update t_car
   <set>
        <if test="name != null and name !=''">name = #{name},</if>
        <if test="sex != null and sex !=''">sex = #{sex},</if>
        <if test="guidePrice != null and guidePrice !=''">guide_price = #{guidePrice},</if>
    </set>
where 
  id = #{id}

五、choose when otherwise标签

这三个标签是在一起使用的:

语法格式

<choose>
  <when></when>
  <when></when>
   <when></when> 
  <otherwise></otherwise> 
</choose> 

相当于java中的

if(){
}else if(){
}else if(){
}else if(){
}else{
}

案例如下:

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

六、foreach标签

foreach标签的属性:

collection:指定数组或者集合

item:代表数组或集合中的元素

separator:循环之间的分隔符

案例如下:

int deleteByIds(Long[] ids);
<delete id="deleteByIds">
        delete from t_car where id in (
          <foreach collection="ids" item="id" separator=",">
              #{id}
          </foreach>
        )
    </delete>

collection=“ids” 这样写会报错,报错信息:[array,arg0]

原因是:如果不指定名称,mybatis默认是传array或者arg0

解决办法1:

<delete id="deleteByIds">
        delete from t_car where id in (
          <foreach collection="array" item="id" separator=",">
              #{id}
          </foreach>
        )
    </delete>

解决办法2:

<delete id="deleteByIds">
        delete from t_car where id in (
          <foreach collection="arg0" item="id" separator=",">
              #{id}
          </foreach>
        )
    </delete>

解决办法3:将接口的参数加上@Param注解,指定名称

int deleteByIds(@Param("ids") Long[] ids);
<delete id="deleteByIds">
        delete from t_car where id in (
          <foreach collection="ids" item="id" separator=",">
              #{id}
          </foreach>
        )
    </delete>

最后再补充一下foreach的 open和close属性

  • open:foreach循环拼接的所有sql语句的最前面以什么开始。
  • close:foreach循环拼接的所有sql语句的最后面以什么结束。

所以上面的sql语句也可以写成这样:

<delete id="deleteByIds">
        delete from t_car where id in 
          <foreach collection="ids" item="id" open="(" close=")" separator=",">
              #{id}
          </foreach>
    </delete>

批量删除的另外一种方式:使用or关键字

<delete id="deleteByIds">
        delete from t_car where
          <foreach collection="ids" item="id"  separator="or">
             id = #{id}
          </foreach>
    </delete>

七、include标签和sql标签

  • sql标签用来声明sql片段
  • include标签用来将声明的sql片段包含到某个sgl语句当中
  • 作用:代码复用。易维护。


相关文章
|
4月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
318 18
|
9月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
8月前
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1118 0
|
4月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
90 0
|
7月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
683 5
|
9月前
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
9月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
10月前
|
SQL XML Java
九、MyBatis动态SQL
九、MyBatis动态SQL
184 2
|
11月前
|
SQL Java 数据库连接
【潜意识Java】MyBatis中的动态SQL灵活、高效的数据库查询以及深度总结
本文详细介绍了MyBatis中的动态SQL功能,涵盖其背景、应用场景及实现方式。
1288 6
|
9月前
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
283 0