Mybatis动态sql之where用法

时间:2025-02-13 20:31:41

      where 主要是用来简化 sql 语句中 where 条件判断,自动地处理 AND/OR 条件,and ,or等关键字可以多不可以没有,多了会自动去掉,少了会报错

        where用来包含多个if的,当多个if有一个成立的时候where会自动增加一个where关键字,并去掉if中多余的and,or等

        使用where标签,在有查询条件中,可以自动添加上where子句;没有查询条件时,不会添加where子句。需值得注意的是:第一个if标签中的sql片段。可以不包含and,不过,写上and或者or也不错,系统会自动将多出的and去掉,但其他if中sql片段的and,必须要求写上否则SQL语句将拼接错误

        语法:<where> 其它动态sql</where>

用法:

@select(
    "select * from student " + 
    "<where>" + 
    "   <if test="name !=null">" + 
    "       name = #{name}" + 
    "   </if>" + 
    "   <if test="age > 100">" + 
    "       or age > #{age}" +
    "   </if>" + 
    "</where>" + 
    "</script>" )
list<Student> getStudentList(@param("name")string name,@param("age")int age)