Mybatis 里的 where、set、trim 标签

动态 Sql 的辅助元素

where、set、trim 作为动态 Sql 的辅助元素,起作用是处理 sql 的封装问题

<where>

常与 <select> 搭配使用

<select id="selectIfandWhereOper" resultMap="BaseResultMap">
	select
	<include refid="Base_Column_List" />
	from t_user a
	<where>
		<if test="email != null and email != ''">
			and a.email like CONCAT('%', #{email}, '%')
		</if>
		<if test="sex != null ">
			and a.sex = #{sex}
		</if>
	</where>
</select>

<where> 有2个作用:

  1. <where> </where>内有 <if> 成立时,加上 where 关键字
  2. 去掉第一个 <if> </if>里的 and 或者 or

<set>

常与 <update> 搭配使用

<update id="updateByPrimaryKeySelective" parameterType="TUser">
	update t_user
	<set>
		<if test="userName != null">
			userName = #{userName,jdbcType=VARCHAR},
		</if>
		<if test="realName != null">
			realName = #{realName,jdbcType=VARCHAR},
		</if>
		<if test="sex != null">
			sex = #{sex,jdbcType=TINYINT},
		</if>
	</set>
	where id = #{id,jdbcType=INTEGER}
</update>

<set> 有2个作用:

  1. 加上 set 关键字
  2. 去掉最后一个 <if> </if> 里的逗号

<trim>

常与 <insert> 搭配使用

<insert id="insertSelective" parameterType="TUser" useGeneratedKeys="true"		keyProperty="id">
	insert into t_user
	<trim prefix="(" suffix=")" suffixOverrides="," >
		<if test="id != null">
			id,
		</if>
		<if test="userName != null">
			userName,
		</if>
		<if test="realName != null">
			realName,
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="id != null">
			#{id,jdbcType=INTEGER},
		</if>
		<if test="userName != null">
			#{userName,jdbcType=VARCHAR},
		</if>
		<if test="realName != null">
			#{realName,jdbcType=VARCHAR},
	</trim>
</insert>

<trim> 有2个作用:

  1. prefix="(" suffix=")" 让前后加上了括号
  2. suffixOverrides="," 去掉最后一个逗号

可以用<trim>表达<where>:
<trim prefix="where" prefixOverrides="and | or ">
神奇的是,和使用 <where> 一样,如果 <if> </if>都不成立,会没有 where 关键字。
但是上面的 prefix="(" suffix=")" ,如果 <if> </if>都不成立,也会有 “(” 和 “)”。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值