MyBatis动态sql

MyBatis实现动态SQL的元素:
元素作用
if常用于根据条件拼接where 子句。
choose (when, otherwise)choose 元素类似 Java 中的 switch 语句。
wherewhere 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入<where></where>子句;而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
setset 元素可以用于动态包含需要更新的列,而删掉无关的逗号。
foreachforeach元素用于对一个集合进行遍历,构建 in 条件语句时常用该元素;foreach 元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。
使用方式:

1、if元素(会自动去掉第一个and):

<select id="select" resultType="com.jd.vo.UserInfo">
	select id,name,mobile,address from user_info where 1=1
	<if test="name!=null and name!=''">
		and name like concat('%',#{name},'%')
	</if>
</select>

2、where元素(where元素在里面的条件成立的时候,才会加入<where></where>元素),可以看出if元素的例子有where 1=1,运用where元素就不需要加1=1:

<select id="select" resultType="com.jd.vo.UserInfo">
	select id,name,mobile,address from user_info
	<where>
		<if test="name !=null and name !=''">
			and name like concat('%',#{name},'%')
		</if>
	</where>
</select>

3、choose (when, otherwise)元素(不能去掉第一个and):

<select id="select" resultType="com.jd.vo.UserInfo">
	select id,name,mobile,address from user_info where 
	<choose>
		<when test="mobile!=null and mobile!=''">
			mobile = #{mobile}
		</when>
		<when test="name !=null and name !=''">
			name like concat('%',#{name},'%')
		</when>
		<otherwise>
			1 = 1
		</otherwise>
	</choose>
</select>

4、set元素, set 元素可以用于动态包含需要更新的列,而删掉无关的逗号(此处去掉了mobile后的逗号):

<update id="update">
	update user_info
	<set>
		<if test="name !=null and name !=''">
			name = #{name},
		</if>
		<if test="mobile!=null and mobile!=''">
			mobile = #{mobile},
		</if>
	</set>
	where id = #{id}
</update>

5、foreach元素,构建 in 条件语句时常用该元素,设置集合项(item)和索引(index)变量:

<!-- 
	collection:指定遍历的集合名:可以用注解@param("")决定所封装的别名
    item:当前遍历的对象名
    open:开始的符号
    close:结束的符号
    separator:遍历元素间的分隔符
 -->
<delete id="delete">
	delete from user_info where id in
	<foreach collection="ids" item="id" open="(" separator="," close=")">
		#{id}
	</foreach>
</delete>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值