动态SQL

SQL的作用:
开发人员在使用JDBC或其他类似的框架进行数据库开发时,通常都要根据需求去手动拼装SQL,这是一个非常麻烦且痛苦的工作,而MyBatis提供的对SQL语句动态组装的功能,恰能很好的解决这一麻烦工作。
动态SQL是MyBatis的强大特性之一,MyBatis3采用了功能强大的基于OGNL的表达式来完成动态SQL。动态SQL主要元素如下表所示:
在这里插入图片描述
在MyBatis中,元素是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择。其基本使用示例如下:

       select * from t_customer where 1=1 
 <if test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
 </if>
 <if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
 </if>

choose、when、otherwise元素

select * from t_customer where 1=1
  <choose>
       <when test="username !=null and username !=''">
                   and username like concat('%',#{username}, '%')
       </when>
       <when test="jobs !=null and jobs !=''">
                   and jobs= #{jobs}
       </when>
       <otherwise>
               and phone is not null
       </otherwise>
  </choose>

<where、trim>元素

 select * from t_customer
 <trim prefix="where" prefixOverrides="and">
        <if test="username !=null and username !=''">
              and username like concat('%',#{username}, '%')
        </if>
        <if test="jobs !=null and jobs !=''">
              and jobs= #{jobs}
        </if>
 </trim
      select * from t_customer
      <where>
           <if test="username !=null and username !=''">
                 and username like concat('%',#{username}, '%')
           </if>
           <if test="jobs !=null and jobs !=''">
                 and jobs= #{jobs}
           </if>
      </where>

set元素:

<update id="updateCustomer"  parameterType="com.itheima.po.Customer">
        update t_customer 
        <set>
            <if test="username !=null and username !=''">
                  username=#{username},
            </if>
            <if test="jobs !=null and jobs !=''">
                  jobs=#{jobs},
            </if>
        </set>
        where id=#{id}
</update>

foreach元素:

 <select id="findCustomerByIds" parameterType="List"
                     resultType="com.itheima.po.Customer">
       select * from t_customer where id in
        <foreach item="id" index="index" collection="list" 
                        open="(" separator="," close=")">
               #{id}
        </foreach>
 </select>

bind元素:

 <select id="findCustomerByName" parameterType="com.itheima.po.Customer"
             resultType="com.itheima.po.Customer">
      <bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'" />
       select * from t_customer 
       where 
       username like #{pattern_username}
 </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值