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语句。在实际应用中,可以根据具体情况选择合适的条件语句来构建动态查询条件。