Mybatis源码分析(八) - 动态sql元素

if 元素:

判断语句 ,单条件分支判断

示例:

<if test="email != null and email != ''">
			 a.email like CONCAT('%', #{email}, '%') and
</if>

Trim、where、set :用于处理sql拼装问题

where示例:

<where>
			<if test="email != null and email != ''">
				and a.email like CONCAT('%', #{email}, '%')
			</if>
			<if test="sex != null ">
				and a.sex = #{sex}
			</if>
</where>

set示例:

<set>
			<if test="userName != null">
				user_name = #{userName,jdbcType=VARCHAR},
			</if>
			<if test="realName != null">
				real_name = #{realName,jdbcType=VARCHAR},
			</if>
			<if test="sex != null">
				sex = #{sex,jdbcType=TINYINT},
			</if>
			<if test="mobile != null">
				mobile = #{mobile,jdbcType=VARCHAR},
			</if>
			<if test="email != null">
				email = #{email,jdbcType=VARCHAR},
			</if>
			<if test="note != null">
				note = #{note,jdbcType=VARCHAR},
			</if>
			<if test="position != null">
				position_id = #{position.id,jdbcType=INTEGER},
			</if>
</set>

trim示例:(前面where和set都可以改成trim)

<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			</if>
			<if test="userName != null">
				user_name,
			</if>
			<if test="realName != null">
				real_name,
			</if>
			<if test="sex != null">
				sex,
			</if>
			<if test="mobile != null">
				mobile,
			</if>
			<if test="email != null">
				email,
			</if>
			<if test="note != null">
				note,
			</if>
			<if test="position != null">
				position_id,
			</if>
</trim>

choose、when、otherwise示例:多条件分支判断

<where>
			<choose>
				<when test="email != null and email != ''">
					and a.email like CONCAT('%', #{email}, '%')
				</when>
				<when test="sex != null">
					and a.sex = #{sex}
				</when>
				<otherwise>
					and 1=1
				</otherwise>
			</choose>
</where>

 

foreach :

在in语句等列举条件常用,常用于实现批量操作

<foreach collection="array" open="(" close=")" item="userName"
            index="i" separator=",">
            #{userName}
</foreach>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值