在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語句,靈活地實現查詢需求。