8、动态SQL
8.1、什么是动态SQL
在MyBatis框架中,动态SQL表示根据特定条件拼接SQL语句的功能,主要通过在映射文件中使用特定的标签来实现。
8.2、if标签
利用if
标签可以进行简单的条件判断,从而进行SQL的拼接,但是漏洞比较大,
<!-- Student selectByDynamicSQL(Student student);-->
<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
标签解决。
8.3、where标签
利用where
标签可以
- 自动判断是否需要where语句,自动动态添加或删除。
- 删除SQL语句之前的and或者or。
如果and或or在SQL语句后面该怎么动态增减?----->用trim
标签。
8.4、trim标签
trim
标签可以理解为where的升级版,这里的动态增加和动态删除是指SQL语句需不需要,确保SQL语句的正确性自动进行的动态增删。
8.5、choose|when|otherwise 标签
choose|when|otherwise
是结合使用,类似于java中的switch|case|default
。
8.6、foreach标签
foreach
标签主要用于批量操作,例如批量删除、批量增加。
根据SQL需要,设置separator|open|close
等属性。
1、批量删除
2、批量添加