若是使用JDBC或者其余框架,不少时候你得根据须要去拼接SQL,这是一个麻烦的事情,而MyBatis提供对SQL语句动态的组装能力,并且它只有几个基本的元素,很是简单明了,大量的判断均可以在MyBatis的映射XML文件里面配置,以达到许多咱们须要大量代码才能实现的功能,大大减小了咱们编写代码的工做量,这体现了MyBatis的灵活性、高度可配置性和可维护性。MyBatis也能够在注解中配置SQL,可是因为注解中配置功能受限,对于复杂的SQL而言可读性不好,因此使用较少。html
关于MyBatis的注解使用能够参考个人这篇文章MyBatis实战之初步java
今天主要讲解这么几个经常使用的动态SQL:数据库
1.if数组
2.choose、when、otherwisemybatis
3.trim、where、set框架
4.foreachide
5.test性能
6.bind单元测试
1、if测试
if一般与where一块儿连用比较多
以下代码所示:
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <where> <if test="userName!=''"> and user_name = #{userName} </if> </where> </select>
<if>中的test一般判断的条件是不等于Null或者空字符串,除此以外还能够进行比较判断好比大于等于小于等这样的。
2、choose、when、otherwise
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <choose> <when test="userName!=null and userName!=''"> where userName = #{userName} </when> <otherwise> where sex = #{sex} </otherwise> </choose> </select>
你能够将<choose><when></when><otherwise></otherwise></choose>理解为Java中的if-else或者是if-else if-else
3、trim、where、set
trim+where示例:
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <trim prefix="where" prefixOverrides="AND |OR"> <if test="userName !=null and userName!=''"> and user_name = #{userName} </if> </trim> </select>
prefix:前缀
prefixoverride:去掉第一个and或者是or
trim+set示例:
update user <trim prefix="set" suffixoverride="," suffix=" where id = #{id} "> <if test="name != null and name.length()>0"> name=#{name} , </if> <if test="gender != null and gender.length()>0"> gender=#{gender} , </if> </trim>
prefix同trim+where的意思是同样,都是前缀。
suffixoverride:去掉最后一个逗号(也能够是其余的标记,就像是上面前缀中的and同样)
suffix:后缀
4、foreach
批量更新示例:
<update id="udpateUserLogoStatu" parameterType="java.util.List"> <foreach collection="users" item="user" index="index" separator=";"> update `user` <set> logo = 1 </set> where logo = #{user.logo} </foreach> </update>
能够参考这篇文章:mybatis的批量更新实例
foreach相关参数解释:
collection配置的users是传递进来的参数名称,它能够是一个数组或者List、Set等集合;
item配置的是循环中当前的元素;
index配置的是当前元素在集合的位置下标;
separator是各个元素的间隔符;
还有代码中没有展现的open和close,它们的含义是以什么符号将这些元素包装起来。
在SQL中对于in语句咱们经常使用,对于大量数据的in语句须要咱们特别注意,由于它会消耗大量的性能,还有一些数据库的SQL对执行的SQL长度也有限制。因此咱们使用它的时候须要预估一下这个collection对象的长度。
5、test
至于test就不提太多了,在<where>+<if>中用到很是频繁。
6、bind
bind一般用于绑定参数,而后引用,在实际开发中用的也很多。
bind的示例:
<select id="getUserList" resultType="com.blog.entity.User"> <!-- bind:能够将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 --> <bind name="userName" value="'%'+userName+'%'"/> eName是employee中一个属性值 SELECT * FROM `user` <if test="userName!=null"> where ename like #{userName} </if> </select>
动态SQL通常常见的问题,就是查询条件出错,通常要么是参数问题,或者是多个字段and拼接出问题。
另外还有一点要提醒,在要用动态SQL以前,最好仍是将SQL先执行一遍,肯定没有问题后,再改成动态SQL,最后再单元测试多个边界条件测试下,确保没有问题后,再编写对应的逻辑Controller。