在 MyBatis 中,<select> 标签用于定义 SQL 查询语句,而 where 条件则是用于过滤查询结果的。通常情况下,我们不需要在 <select> 标签中直接编写 where 条件,因为 MyBatis 会自动处理查询参数。但是,在某些情况下,我们可能需要手动指定 where 条件,这时可以通过以下两种方式实现:
<if> 标签判断条件是否为空,如果不为空,则添加 where 子句。<select id="findUserById" parameterType="int" resultType="User"> SELECT * FROM user <where> <if test="id != null"> AND id = #{id} </if> </where> </select> 在这个例子中,如果 id 参数不为空,MyBatis 会自动生成一个带有 WHERE 子句的 SQL 查询语句。
<choose>、<when> 和 <otherwise> 来实现更复杂的条件判断。<select id="findUserByIdAndName" parameterType="map" resultType="User"> SELECT * FROM user <where> <choose> <when test="id != null"> AND id = #{id} </when> <when test="name != null and name != ''"> AND name = #{name} </when> <otherwise> <!-- 这里可以添加默认的查询条件,例如: --> AND age = 18 </otherwise> </choose> </where> </select> 在这个例子中,我们根据 id 和 name 参数的值来动态生成 where 子句。如果 id 不为空,则添加 id = #{id} 条件;如果 name 不为空且不为空字符串,则添加 name = #{name} 条件;否则,添加一个默认的查询条件 age = 18。
总之,MyBatis 的 <select> 标签与 where 条件的搭配使用可以通过 <if> 标签或动态 SQL 标签来实现。在实际开发中,根据需求选择合适的方式来实现条件过滤。