Mybatis的几种标签

where标签

<select id="findUserList" parameterType="queryVo" resultType="user">
	 	 SELECT * FROM user
	 	 <!-- where标签会处理它后面的第一个and -->
	 	 <where>
	 	 	 <if test="user != null">
	 	 	 	 <if test="user.username != null and user.username != ''">
	 	 	 	 	 AND username like '%${user.username}%'
	 	 	 	 </if>
	 	 	 </if>
	 	 </where>
</select>

include标签

映射文件中可使用sql标签将重复的sql提取出来,然后使用include标签引用即可,最终达到sql重用的目的

将where条件抽取出来:

<sql id="query_user_where">
	 	 <if test="user != null">
	 	 	 <if test="user.username != null and user.username != ''">
	 	 	 	 AND username like '%${user.username}%'
	 	 	 </if>
	 	 </if>
</sql>

使用include引用:

<!-- 使用包装类型查询用户 使用ognl从对象中取属性值,如果是包装对象可以使用.操作符来取内容部的属性 -->
<select id="findUserList" parameterType="queryVo" resultType="user">
	 	 SELECT * FROM user
	 	 <!-- where标签会处理它后面的第一个and -->
	 	 <where>
	 	 	 <include refid="query_user_where"></include>
	 	 </where>
</select>

如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:

<include refid="namespace.sql片段”/>

foreach标签

<if test="ids != null and ids.size() > 0">
	<!-- collection:指定输入的集合参数的参数名称 -->
	<!-- item:声明集合参数中的元素变量名 -->
	<!-- open:集合遍历时,需要拼接到遍历sql语句的前面 -->
	<!-- close:集合遍历时,需要拼接到遍历sql语句的后面 -->
	<!-- separator:集合遍历时,需要拼接到遍历sql语句之间的分隔符号 -->
	<foreach collection="ids" item="id" open=" AND id IN (" close=" ) " separator=",">
		#{id}
	</foreach>
</if>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值