在MyBatis中,可以使用动态SQL来根据条件动态构建SQL语句。以下是使用动态条件的一些常见方法:
<select id="selectUsers" parameterType="map" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<select id="selectUsers" parameterType="map" resultType="User">
SELECT * FROM users
<where>
<choose>
<when test="username != null">
AND username = #{username}
</when>
<when test="age != null">
AND age = #{age}
</when>
<otherwise>
AND 1=1
</otherwise>
</choose>
</where>
</select>
<select id="selectUsers" parameterType="map" resultType="User">
SELECT * FROM users
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</trim>
</select>
通过以上方法,可以根据不同的条件动态构建SQL语句,灵活地实现查询需求。