<!-- 4.2 choose用法 需求: 在已有的sys_user表中,除了主键id外,我们认为user_name也是唯一的, 所有的用户名都不可以重复。现在进行如下查询:当参数id有值的时候,优先 使用id查询,如果id没有值的时候,就判断用户名是否有值,如果用户名有值 就使用用户名查询,如果用户名也没有值,就使SQL查询无结果。 --> <select id="selectByUserName" resultType="tk.mybatis.simple.model.SysUser"> select id, use_name userName, user_password userPassword, user_email userEmail, user_info userInfo, head_img headImg, create_time createTime from sys_user where 1=1 <choose> <when test="id!=null"> and id = #{id} </when> <when test="userName!=null and userName!=''"> and user_name = #{userName} </when> <otherwise> and 1=2 </otherwise> </choose> </select>
From《MyBatis从入门到精通》