mybatis(三):动态sql

一、if标签;携带了哪个字段查询条件就带上这个字段的值

语法:

<select id="getUsersByConditionIf" resultType="com.yjr.mybatis.bean.User">
  select * from tb_user
  <where>
    <if test="name!=null and name!='' ">
    and name like #{name}
    </if>
    <if test="lastName!=null and lastName!='' ">
      and lastName = #{lastName}
    </if>
  </where>
</select>

二、choose (when, otherwise):分支选择;如果带了id就用id查,如果带了name就用name查;只会进入其中一个

select id="getUsersByConditionChoose" resultType="com.yjr.mybatis.bean.User">
  select * from tb_User
  <where>
    <choose>
      <when test="id!=null">
        id=#{id}
      </when>
      <when test="name!=null">
        name like #{name}
      </when>
      <otherwise>
        1 = 1
      </otherwise>
    </choose>
  </where>
</select>

三、set(封装修改条件)

<update id="updateUser">
  update tb_user
  <set>
  <if test="name!=null">
    name=#{name},
  </if>
  <if test="email!=null">
    email=#{email},
  </if>
  </set>
  where id = #{id}
</update>

四、foreach遍历;

collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素

<select id="getUsersByConditionForeach" resultType="com.yjr.mybatis.bean.User">
  select * from tb_user
  <foreach collection="ids" item="item_id" separator=","
  open="where id in(" close=")">
    #{item_id}
  </foreach>
</select>

五、批量保存

<insert id="addUser">
  insert into tb_user(name,email)
  values
  <foreach collection="users" item="user" separator=",">
    (#{user.name},#{user.email})
  </foreach>
</insert>

转载于:https://www.cnblogs.com/dwxblogs/p/10841350.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值