动态 SQL 是指可以根据不同的参数信息来动态拼接的不确定的 SQL 叫做动态 SQL,MyBatis 动态 SQL 的主要元素有:if、choose/when/otherwise、trim、where、set、foreach 等。
以 if 标签的使用为例:
<select id="findUser" parameterType="com.interview.entity.User" resultType="com.interview.entity.User">
select * from t_user where 1=1
<if test="id!=null">
and id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
</select>
当调用此方法时,如果传递 id 参数了,那么生成的 SQL 是这样的:
select * from t_user where 1=1 and id=n
如果不传递 id 参数,那么生成的 SQL 是这样的:
select * from t_user where 1=1
这就是动态 SQL,根据不同的参数生成不同的 SQL 语句。