mybatis动态sql(if,where,sql片段)

Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的。

sql片段定义: 

        <sql id="selector">
		select * from user
	</sql>

使用:

<include refid="selector"></include>

 where 可以去掉第一个前 and

	<select id="queryUserWhere" parameterType="com.it.mybatis.pojo.User" resultType="com.it.mybatis.pojo.User">
		<include refid="selector"></include>
		<where>
			<if test="sex != null and sex !=''">
				and sex = #{sex}
			</if>
			<if test="username != null and username !=''">
				and username = #{username}
			</if>
		</where>
	</select>

 

foreach标签

1)foreach标签,进行遍历

2)collection:遍历的集合,这里是类的 id 属性

3)item:遍历的项目,可以随便写,和后面的#{}里面要一致

4)open:在前面添加的sql片段

5)close:在结尾处添加的sql片段

6)separator:指定遍历的元素之间使用的分隔符

如果不用包装类,集合,数组--》collection=list  ,array

	<select id="queryUserById" parameterType="com.it.mybatis.pojo.QueryVo" resultType="com.it.mybatis.pojo.User">
		<include refid="selector"></include>
		<where>
			<foreach collection="id" item="id" 
				open="id in (" close=")" separator=",">
				#{id}
			</foreach>
		</where>
	</select>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值