动态SQL中if,choose,when,otherwise,trim等用法

if用法

	<!-- 使用if元素根据条件动态查询用户信息 -->
	<select id="selectUserByIf" resultType="com.po.MyUser"
		parameterType="com.po.MyUser">
		select * from user where 1=1
		<if test="uname!=null and uname!=''">
			and uname like concat('%',#{uname},'%')
		</if>
		<if test="usex!=null and usex!=''">
			and usex=#{usex}
		</if>
	</select>

choose,when,otherwise用法

<!-- 使用choose、when、otherwise元素根据条件动态查询用户信息 -->
	<select id="selectUserByChoose" resultType="com.po.MyUser" parameterType="com.po.MyUser">
		select * from user where 1=1
		<choose>
		<when test="uname!=null and uname!=''">
			and uname like concat('%',#{uname},'%')
		</when>
		<when test="usex!=null and usex!=''">
			and usex=#{usex}
		</when>
		<otherwise>
			and uid > 10
		</otherwise>
		</choose>
	</select>

set元素

	<!-- 使用set元素动态修改一个用户 -->
	<update id="updateUserBySet" parameterType="com.po.MyUser">
		update user
		<set>
			<if test="uname!=null">uname=#{uname},</if>
			<if test="usex!=null">usex=#{usex}</if>
		</set>
		where uid=#{uid}
	</update>

foreach元素

item:集合中每一个元素进行迭代时的别名
index:指定一个名字,用于表示在迭代过程中每次迭代到的位置
open:该语句以什么开始
separator:在每次进行迭代之间以什么符号作为分隔符
close:以什么解释
collection为必选属性,但是特别容易出错

	<!-- 使用foreach元素查询用户信息 -->
	<select id="selectUserByForeach" resultType="com.po.MyUser"
		parameterType="List">
		select * from user where uid in
		<foreach collection="list" item="item" index="index" open="("
			separator="," close=")">
			#{item}
		</foreach>
	</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值