MyBatis的XML文件支持動態SQL的方式有以下幾種:
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
</where>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<choose>
<when test="username != null">
AND username = #{username}
</when>
<otherwise>
AND id = #{id}
</otherwise>
</choose>
</where>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users
WHERE id IN
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<trim prefix="AND" prefixOverrides="AND" suffixOverrides="OR">
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
OR email = #{email}
</if>
</trim>
</where>
</select>
通過以上方式,MyBatis的XML文件可以靈活地支持動態SQL,根據不同的條件生成不同的SQL語句,實現更加靈活和強大的SQL操作。