MyBatis條件語句是在SQL語句中使用的條件判斷語句,用于動態生成查詢條件。以下是一些MyBatis條件語句的最佳實踐:
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<choose>
<when test="name != null">
AND name = #{name}
</when>
<when test="age != null">
AND age = #{age}
</when>
<otherwise>
AND 1 = 1
</otherwise>
</choose>
</where>
</select>
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
AND id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
<select id="selectUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<trim prefix="AND" prefixOverrides="AND">
<if test="name != null">
name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</trim>
</where>
</select>
這些是MyBatis條件語句的一些最佳實踐,可以幫助你更靈活地生成動態SQL語句。在實際應用中,可以根據具體情況選擇合適的條件語句來構建動態查詢條件。