MyBatis 动态SQL

在MyBatis在SQL映射文件中可以灵活、智能的动态SQL来实现SQL映射。

有以下方案:

1.if+set:完成更新操作

2.if+where:完成多条件查询

3.if+trim:完成多条件查询(替代where)或者更新操作(替代set)

4.foreach:完成复杂查询、主要用在in条件查询中,迭代集合。

5.choose:完成条件查询,好比Java中switch一样。


例子:在xml文件中 if+trim实现

<update id="ProviderUpdateById" parameterType="Provider">
  update smbms_provider
  <trim prefix="set" suffixOverrides="," suffix="where id =#{id}">
   <if test="proCode != null">proCode=#{proCode},</if>
   <if test="proName != null">proName=#{proName},</if>
   <if test="proDesc != null">proDesc=#{proDesc},</if>
   <if test="proContact != null">proContact=#{proContact},</if>
   <if test="proPhone != null">proPhone=#{proPhone},</if>
   <if test="proAddress != null">proAddress=#{proAddress},</if>
   <if test="proFax != null">proFax=#{proFax},</if>
   <if test="modifyDate != null">modifyDate=#{modifyDate},</if>
   <if test="modifyBy != null">modifyBy=#{modifyBy},</if>
  </trim>
 </update>

例子2:在xml文件中 choose实现

<select id="getProviderList_choose" resultType="Provider">
  select * from smbms_provider where 1=1
  <choose>
   <when test="proCode != null and proCode!= ''">
    and proCode=#{proCode}
   </when>
   <when test="proName!=null and proName!= ''">
    and proName=#{proName}
   </when>
   <when test="proContact != null and proContact!=''">
    and proContact=#{proContact}
   </when>
   <otherwise>
     and YEAR(creationDate) =YEAR(#{creationDate})
   </otherwise>
  </choose>

例子3:在xml文件中 foreach实现 

<select id="getUserByRoleId_foreach_map" resultMap="userMapByRole">
  select * from smbms_user where userRole in
  <foreach collection="rKey" item="roleMap" open="(" separator="," close=")">
   #{roleMap}
  </foreach>
 </select>

注意:此处foreach的collection为map集合的KEY值

MyBatis对sql操作非常强大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值