mybatis的动态SQL(二)choose标签的使用

来源:互联网 发布:api python 编辑:程序博客网 时间:2024/06/08 11:21

上一篇中我们讲解了if标签的使用,但是他无法实现if…else的逻辑判断,这就要用到我们这一篇提到的choose when otherwise标签。

使用规则:

一个choose中至少有一个when,有0个或一个otherwise

举个例子:

<select id="selectByIdOrUserName" resultType="cd.mybatis.model.SysUser">select id,    user_name userName,    user_password UserPassword,    user_info userInfofrom sys_userwhere 1=1<choose>    <when test="id!=null">       and id=#{id}    </when>    <when test="userName !=null and userName !='' ">       and user_name =#{uerName}    </when>    <otherwise>       and 1=2    </otherwise> </choose></select>

代码解释:

查询用户的信息,如果提供了id,那么优先使用id查询,如果没有id,提供了username,那么使用username作为条件查询,如果都没有则执行otherwise,确保返回值的正确

原创粉丝点击