if标签是与(and)的关系,只要test中的表达式为 true,就会执行 if 标签中的条件;而 choose 是或(or)的关系,并不想应用所有的条件,而只是想从多个选项中选择一个。

        choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

<!--  按顺序将实体类 User 第一个不为空的属性作为:where条件 -->  
@select("<script>"+
        "SELECT *  "+
        "  FROM User u   "+
        "<where> "+
        "   <choose>"+
        "       <when test='username !=null '>  "+
        "            u.username LIKE CONCAT('%', #{username})  "+
        "       </when >  "+
        "       <when test='sex != null and sex != '' '>  "+
        "            AND u.sex = #{sex}" +
        "       </when >  "+
        "       <when test='birthday != null '>  "+
        "            AND u.birthday = #{birthday}  " +
        "       </when >  "+
        "       <otherwise>  "+
        "       </otherwise>  "+
        "   </choose> "+
        "</where>   "+
        "</script>")  
  
  
@select("<script>"+
        "SELECT *  "+
        "  FROM User u   "+
        " WHERE 1 = 1" + //为了保证sql不报错建议使用<where>
        "   <choose>"+
        "       <when test='title != null'>  "+
        "            and title = #{title} " +
        "       </when >  "+
        "       <when test='content != null '>  "+
        "            and content = #{content} " +
        "       </when >  "+
        "       <otherwise>  "+
        "            and owner = "owner1" " +
        "       </otherwise>  
        "   </choose> "+
        "</script>")
<where>使用用法点击该句可直接查看
          
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐