MyBatis中的动态SQL可以通过if
、choose
、when
、otherwise
、trim
、where
、set
、foreach
等标签实现。以下是一些常用的动态SQL示例:
if
标签实现条件判断:<select id="findUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="name != null">
AND name = #{name}
</if>
</where>
</select>
trim
标签处理SQL语句中的多余的AND或OR:<select id="findUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<trim prefix="AND" prefixOverrides="AND">
<if test="id != null">
id = #{id}
</if>
<if test="name != null">
AND name = #{name}
</if>
</trim>
</where>
</select>
choose
、when
、otherwise
标签实现条件选择:<select id="findUser" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<choose>
<when test="id != null">
AND id = #{id}
</when>
<when test="name != null">
AND name = #{name}
</when>
<otherwise>
AND status = 1
</otherwise>
</choose>
</where>
</select>
foreach
标签处理集合参数的循环:<select id="findUserByIds" parameterType="list" resultType="User">
SELECT * FROM user
WHERE id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
通过以上示例,可以根据不同的条件动态拼接SQL语句,实现灵活的查询操作。在实际开发中,可以根据具体需求结合不同的标签来编写动态SQL。