2 MyBatis动态sql之where标签|转

1 MyBatis动态SQL之if 语句
2 MyBatis动态sql之where标签|转
3 MyBatis动态SQL之set标签|转
4 MyBatis动态SQL之trim元素|转
5 MyBatis动态sql中foreach标签的使用
6 MyBatis动态SQL之choose(when、otherwise)语句
7 MyBatis动态SQL之bind标签|转

  where标签的作用类似于动态sql中的set标签,主要用来简化sql语句中where条件,使得MyBatis 自动判断是否需要加where语句,并且避免在查询条件开头强制添加类似WHERE state = 'ACTIVE'语句之后,才可以添加if标签。

  使用案例如下所示:

   <select id="selectByParams" parameterType="map" resultType="user">
    select * from user
    <where>
      <if test="id != null ">and id=#{id}</if>
      <if test="name != null and name.length()>0" >and name=#{name}</if>
      <if test="gender != null and gender.length()>0">and gender = #{gender}</if>
            and state = 'ACTIVE'
    </where>
   </select>

  案例解析:按照标准写法,第一个标签内应该不写 and,但是,即便写了and也不会报错,因为where标签自动地帮助我们移除了第一个and关键字。温馨提示,第二个之后的标签内,必须有 and 关键字。

  where标签只有在一个以上的if条件有值的情况下,才去主动添加WHERE子句。而且,若紧邻where关键字的内容是“AND”或“OR”开头,则where标签自动把它们去除。例如,在上述SQL中,如果只有查询条件id的值为null,那么控制台打印出来的SQL为:

select * from user where name="xx" and gender="yy";

posted @ 2022-03-30 08:05  楼兰胡杨  阅读(1332)  评论(0编辑  收藏  举报