MyBatis实战之动态SQL

 如果使用JDBC或者其他框架,很多时候你得根据需要去拼接SQL,这是一个麻烦的事情,而MyBatis提供对SQL语句动态的组装能力,而且它只有几个基本的元素,非常简单明了,大量的判断都可以在MyBatis的映射XML文件里面配置,以达到许多我们需要大量代码才能实现的功能,大大减少了我们编写代码的工作量,这体现了MyBatis的灵活性、高度可配置性和可维护性。MyBatis也可以在注解中配置SQL,但是由于注解中配置功能受限,对于复杂的SQL而言可读性很差,所以使用较少。

关于MyBatis的注解使用可以参考我的这篇文章

    <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或者空字符串,除此之外还可以进行比较判断比如大于等于小于等这样的。

 

二、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

 

三、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:后缀

 

四、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>       &
                    
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信