MyBatis-动态SQL-if and where

动态SQL

  • 随着用户的输入或外部条件的变化而变化的SQL语句,我们称之为动态SQL语句

  •  
  •         select *
            from emp
            where name like concat('%', #{name}, '%')
              and gender = #{gender}
              and entrydate between #{begin} and #{end}
            order by update_time desc;
  • 在上述的SQL语句中,只有在姓名、性别、入职日期三个条件都进行设定之后,才能进行正确的查询,但是如果想单独实现某一个条件的查询,就需要使用动态的SQL语句

if标签

  • <if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL
  • 改造后的SQL语句为
    •         select *
              from emp
              where
              <if test="name!=null">
                  name like concat('%', #{name}, '%')
              </if>
              <if test="gender!=null">
                  and gender = #{gender}
              </if>
              <if test="begin!=null and end!=null">
                  and entrydate between #{begin} and #{end}
              </if>
              order by update_time desc;
  • 运行如下方法

    •     public void TestList() {
              List<Emp> list = empMapper.List("张", null, null, null);
              System.out.println(list);
          }
    • 只传递name属性

  • 运行结果如下

    • 将所有张姓员工信息都查询出来了

  • 存在问题​​​​​

    • 当查询条件中name为null时,就会报出语法错误如下:

    •  
    • 在where之后含有and关键字,出现语法错误
  • 问题解决
    • 在XML映射文件的SQL语句中加入<where>标签
    • 具体代码如下:
    •         select *
              from emp
              <where>
                  <if test="name!=null">
                      name like concat('%', #{name}, '%')
                  </if>
                  <if test="gender!=null">
                      and gender = #{gender}
                  </if>
                  <if test="begin!=null and end!=null">
                      and entrydate between #{begin} and #{end}
                  </if>
              </where>
              order by update_time desc;
    • 运行结果如下:

小结

  • <if>标签:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL语句
  • <where>标签:where元素只会在子元素有内容的情况下才插入where子句,而且自动去除子句开头的and或者or

猜你喜欢

转载自blog.csdn.net/weixin_64939936/article/details/132112415