在MyBatis框架中,动态SQL表示根据特定条件拼接SQL语句的功能,主要通过在映射文件中使用特定的标签来实现。
利用if标签可以进行简单的条件判断,从而进行SQL的拼接,但是漏洞比较大,
<select id="selectByDynamicSQL" resultType="Student">
select * from t_student where
<if test="sId != null and sId != ''">
s_id = #{sId}
if>
<if test="sName != null and sName != ''">
and s_name = #{sName}
if>
<if test="sAge != null and sAge != ''">
and s_age = #{sAge}
if>
<if test="sSex != null and sSex != ''">
and s_sex = #{sSex}
if>
select>
比如条件全部成立,where就变得多余了。----解决---->利用where标签
又比如第一个条件不成立其他条件成立,则又多出了一个and。 ----解决---->利用where或trim标签解决。
利用where标签可以

如果and或or在SQL语句后面该怎么动态增减?----->用trim标签。
trim标签可以理解为where的升级版,这里的动态增加和动态删除是指SQL语句需不需要,确保SQL语句的正确性自动进行的动态增删。

choose|when|otherwise 是结合使用,类似于java中的switch|case|default。

foreach标签主要用于批量操作,例如批量删除、批量增加。
根据SQL需要,设置separator|open|close等属性。
1、批量删除

2、批量添加
