myBatis动态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>

2. choose, when, otherwise

<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”>
			SELECT * FROM BLOG WHERE state = 'ACTIVE'
			<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>

3. trim, where, set

1. where 

where 元素知道如果由被包含的标记返回任意内容,就仅仅插入“ WHERE”。而且,如果以“ AND”或“ OR”开头的内容,那么就会跳过 WHERE 不插入。

<select id=”findActiveBlogLike”
				parameterType=”Blog” resultType=”Blog”>
				SELECT * FROM BLOG
				<where>
					<if test=”state != null”>
						state = #{state}
					</if>
					<if test=”title != null”>
						AND title like #{title}
					</if>
				</where>
			</select>

2. set

<update id="updateAuthorIfNecessary" parameterType="domain.blog.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>
						<if test="bio != null">bio=#{bio}</if>
					</set>
				where id=#{id}
			</update>

3. trim

	如果 where 元素没有做出你想要的,你可以使用 trim 元素来自定义。
	比如,和 where元素相等的 trim 元素是:
		<trim prefix="WHERE" prefixOverrides="AND |OR ">
					</trim>
	对和set相等的 trim 元素,它看起来就是这样的:
		<trim prefix="SET" suffixOverrides=",">
					</trim>
	overrides 属性采用管道文本分隔符来覆盖,这里的空白也是重要的。
	它的结果就是移除在overrides属性中指定的内容,插入在 with 属性中的内容。

4. foreach

	动态 SQL通用的必要操作是迭代一个集合,通常是构建在IN条件中的
<select id="selectPostIn" resultType="domain.blog.Post">
			SELECT * FROM POST P
			WHERE ID in
			<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
			#{item}
			</foreach>
		</select>
	1. foreach 元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。
	2. 它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。
	3. 这个元素是很智能的,它不会偶然地附加多余的分隔符。
	4. 你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。
		当你这么做的时候, MyBatis 会自动将它包装在一个 Map 中,用名称作为键。 
		List 实例将会以“ list”作为键,而数组实例将会以“ array”作为键。

foreach-insert

<select id="insertOrderDish" parameterType="java.util.List">

  insert into
  ordersdish(id,ordersId,dishId)
  values
  <foreach collection="list" item="item" index="index"
   separator=",">
   (#{item.id,jdbcType=VARCHAR},#{item.orderId,jdbcType=BIGINT},#{item.dishId,jdbcType=INTEGER})
  </foreach>
 </select>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值