一,动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦!
(一)不使用mybatis动态sql 来书写的代码是这样的
<select id="selectStudent" resultType="student" parameterType="cn.kgc.mybatis.pojo.Student">
select * from user where stu_no=#{stuNo} and stu_name=#{stuName} and stu_sex=#{stuSex}
</select>
不使用动态sql语句,如果 #{stu_name} 为空,那么查询结果也是空,解决的方法由下
(二)使用动态SQL语句 if 的方式
<select id="search" resultType="student">
select * from student
<trim prefix="where" prefixOverrides="and">
<if test="stuNo!=null">
stu_no = #{stuNo}
</if>
<if test="stuName!=null">
and stu_name = #{stuName}
</if>
<if test="stuSex!=null">
and stu_sex = #{stuSex}
</if>
</trim>
</select>
使用mybatis动态sql哪怕 #{stu_name} 为空,那么因为有了if语句的判断 stu_name!=null ,所以sql语句依旧会继续执行,以及并不会出现null值,直至于语句结束,所以动态sql更方便了我们的sql语句代码的书写。
使用了mybatis动态sql可以更简便的让我们使用,可以更好的理解sql语句,可以让sql语句变得更有扩展性,一条sql语句可以供更多的方法去使用。