天天看点

myBatis xml if、where、if-else?、foreach 心得ifwhereif-else =>> choose, when, otherwise

文章转载自:https://blog.csdn.net/qq_34886018/article/details/86478403

       MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

       虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。

       动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

if

       mapper中编写sql,使用

<if test = ' '> </if>

,可以使你的接口很便捷

举个栗子:

select * from student
<if test = " id != null ">
     where student.id =#{id}
</if>
           

       一个

<if>

标签还是不够用的,你单独使用

<if>

的时候肯定还会遇到这样的问题

select * from student
where
<if test = " id != null ">
student.id = #{id}
</if>
<if test = " name != null and name != '' ">
and student.name = #{name}
</if>
           

       如果当你的id为空时,

name

前面的

and

是没有必要的,运行会抛异常

或者当这两个

<if>

都为空时,只剩一个空的where,还是会报错

where

select * from student
<where>
<if test = " id != null ">
    and student.id = #{id}
</if>
<if test = " name != null and name != '' ">
    and student.name = #{name}
</if>
</where>
           

       where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入WHERE子句。而且,若语句的开头为AND或OR,where 元素也会将它们去除。

if-else =>> choose, when, otherwise

       首先,在myBatis中是不支持if-else的,想要是用if-else的话,可以使用choose代替。

choose,when,otherwise有点像Java中的switch

<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>
           

关于mybatis的动态sql,建议查看,中文哦官方文档