MyBatis中也提供了类似iBATIS的动态SQL功能,可以通过使用if、choose、foreach等标签来实现。
例如,可以使用if标签来实现条件判断:
<select id="selectUsers" parameterType="map" resultType="User"> SELECT * FROM users <where> <if test="username != null"> AND username = #{username} </if> </where></select>可以使用choose标签实现条件选择:
<select id="selectUsers" parameterType="map" resultType="User"> SELECT * FROM users <where> <choose> <when test="username != null"> AND username = #{username} </when> <otherwise> AND age >= #{age} </otherwise> </choose> </where></select>可以使用foreach标签实现循环操作:
<select id="selectUsers" parameterType="map" resultType="User"> SELECT * FROM users <where> <foreach collection="ids" item="id" separator="OR"> id = #{id} </foreach> </where></select>通过以上方式,可以实现类似iBATIS的动态SQL功能。


