MyBatis动态SQL

动态SQL
MyBatis的动态SQL,解决了SQL字符串拼接的痛苦。

1.if
<select id="findActiveBlogWithTitleLike"
	parameterType="Blog" resultType="Blog">
	SELECT * FROM BLOG
	WHERE state = 'ACTIVE'
	<if test="title != null">
		AND title like #{title}
	</if>
</select>


这条一句会提供一个可选的文本查找功能。如果没有传递title,那么所有激活的博客都会被返回。
如果传递了title,那么就会查找相近的title。


2.choose,when,otherwise
<select id="findActiveBlogLike"
	parameterType="BLOG" resultType="BLOG">
	SELECT * FROM BLOG
	WHERE
	<choose>
		<when test="title != null">
			AND title like #{title}
		</when>
		<when test="author != null and author.name != null">
			AND title like #{author.name}
		</when>
		<otherwise>
			AND featured = 1
		</otherwise>
	</choose>
</select>


注:如果上述条件都没有匹配,则会变成SELECT * FROM BLOG WHERE
如果仅有第二个匹配,则会变成SELECT * FROM BLOG WHERE AND title LIKE somelike
显然这样会查询失败。要解决这个问题,mybatis提供了解决方法。
<select id="findActiveBlogLike"
	parameterType="BLOG" resultType="BLOG">
	SELECT * FROM BLOG
	WHERE
	<trim prefix="WHERE" prefixOverrides="AND |OR ">
		<choose>
			<when test="title != null">
				AND title like #{title}
			</when>
			<when test="author != null and author.name != null">
				AND title like #{author.name}
			</when>
			<otherwise>
				AND featured = 1
			</otherwise>
		</choose>
	</trim>
</select>


overrides属性采用管道文本分隔符来覆盖,这里的空白是重要的。它的结果就是移除在InnerText中overrides中指定的内容。


3.set
<update id="updateAuthorIfNecessary"
	parameterType="Author">
	update Author
	<set>
		<if test="username != null">username=#{username},</if>
		<if test="password != null">password=#{password},</if>
		<if test="email != null">email=#{email}</if>
	</set>
	where id=#{id}
</update>


同上的问题,优化后:
<update id="updateAuthorIfNecessary"
	parameterType="Author">
	update Author
	<trim prefix="where" prefixOverrides=","> 
	<set>
		<if test="username != null">username=#{username},</if>
		<if test="password != null">password=#{password},</if>
		<if test="email != null">email=#{email}</if>
	</set>
	where id=#{id}
	</trim>
</update>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值