MyBatis动态sql

sql语句的书写中长需要动态的参数以及条件。在Mybatis中,利用动态 SQL可以很方便地根据不同条件拼接SQL语句。

 

  •  if标签
<if test="userName!=null">
	and user_name like #{userName}
</if>

if标签通过对test内条件进行判断,如果成功执行标签内语句,反之不执行。


  • where标签

 where 元素只会在至少有一个子元素的条件返回 SQL子句的情况下才去插入“where”子句;

与 if标签嵌套使用如下

<select id="select" resultType="User">
	select id,user_name,mobile,address 
	from user_info
	<where>
		<if test="userName!=null">
			and user_name like #{userName}
		</if>
		<if test="mobile!=null">
			and mobile like #{mobile}
		</if> 
	</where>
</select>

  • set标签

set 元素可以用于动态包含需要更新的列,而删掉无关的逗号。

与update标签嵌套使用如下

<update id="update">
	update user_info
	<set>
		<if test="userName!=null">
			user_name = #{userName}
		</if>
		<if test="mobile!=null">
			mobile = #{mobile}
		</if>
	</set>
	where id = #{id} 
</update>

update语句书写格式:update 表名称 set 列名称 = 新值 where 列名称 = 某值


  • foreach

​​​​​​​foreach元素用于对一个集合进行遍历,构建 in 条件语句时常用该元素;foreach元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。

格式如下

<select id="selectPostIn" resultType="domain.blog.Post">
  select * from user_info
  WHERE ID in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

例子

<delete id="delete">
	delete from user_info where id in
	<foreach item="id" collection="ids" open="(" separator="," close=")">
		#{id}
	</foreach>
</delete>

​​​​​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值