强大的动态SQL

1.首先,什么是动态SQL? 动态SQL有什么作用?

  传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。
  Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发效率。
2.动态SQL常用的元素:
 
元素 作用 备注
if 判断语句 单条件分支判断
choose(when,otherwise) 相当于java中的switchcase语句 多条件分支判断
teim 辅助元素,用于处理特定的SQL拼装问题 用于处理SQL拼装的问题
foreach 迭代循环语句 在in语句条件常用
 
3.带大家进入代码
Øif元素

  if元素是最常用的判断语句,相当于Java中国的 if 语句,它常常与test属性联合使用。

<select id="findRole1" parameterType="string" resultMap="roleResultMap">
    select role_no, role_name, note from t_role where 1=1
    <if test="roleName != null and roleName !=''">
      and role_name like concat('%', #{roleName}, '%')
    </if>
  </select>

Øchoose、when、otherwise元素

    如果在判断时有更多的选择,不只是两种选择,也就是类似switch...case...default...功能的语句。在映射的SQL语句中,使用choose、when、otherwise元素承担这个功能。

<select id="findRole2" parameterType="role" resultMap="roleResultMap">
    select role_no, role_name, note from t_role
    where 1=1
    <choose>
      <when test="roleNo != null and roleNo !=''">
        AND role_no = #{roleNo}
      </when>
      <when test="roleName != null and roleName !=''">
        AND role_name like concat('%', #{roleName}, '%')
      </when>
      <otherwise>
        AND note is not null
      </otherwise>
    </choose>
  </select>

上述的场景就是:

  首先,如果角色编号不为空,则只用角色编号作为条件查询。

  当角色编号为空,而角色名称不为空,则使用角色名称作为条件进行模糊查询。

  当角色编号和角色编号都为空,则要求角色备注不为空。

Øtrim、where元素

<select id="findRole3" parameterType="role" resultMap="roleResultMap">
    select role_no, role_name, note from t_role
    <where>
      <if test="roleName != null and roleName !=''">
        and role_name like concat('%', #{roleName}, '%')
      </if>
      <if test="note != null and note !=''">
        and note like concat('%', #{note}, '%')
      </if>
    </where>
  </select>

  有时需要去掉一些特殊的SQL语法,比如常见的and、or等。使用trim元素也可以达到预期效果。其中prefix代表的语句的前缀,prefixOverrides代表的是需要去掉哪种字符串。与前面的where语句是等效的。

Øforeach元素

<select id="findRoleByNums" resultMap="roleResultMap">
    select role_no, role_name, note from t_role where role_no in
    <foreach item="roleNo" index="index" collection="roleNoList"
      open="(" separator="," close=")">
      #{roleNo}
    </foreach>
  </select>

f oreach元素是一个循环语句,它的作用是遍历集合,

 它能很好的支持数组和List、Set接口的集合,对此提供遍历的功能,它往往用于SQL中的in关键字。

 collection配置的roleNoList是传递进来的参数名称,它可以是一个数组、List、Set等集合。

  item配置的是循环中当前的元素。

  index配置的是当前元素在集合的位置下标。

  open和close配置的是以什么符号将这些集合元素包装起来。

  separator是各个元素的分隔符。


    以上就是我在学习过程中对于Mybatis中的动态SQL语句的常见的一些知识点总结,希望大家有一些帮助,更希望大家可以一起学习进步!

    作为一名即将成为程序员的我来说,每天坚持的东西就是写代码,我坚信坚持了就一定会有收获。

    那些看似波澜不惊的日复一日,会突然在每一天让你看到坚持的意义。

原文地址:https://www.cnblogs.com/dyywht/p/13964820.html