mybatis的动态sql-if和sql片段 foreach的使用

当查询条件有多个的时候,可以使用动态sql


例如像这种需求:

SELECT * FROM USER  WHERE id=#{id} and sex=#{sex}

的时候,当传入id的值为空时,用这种方式写sql语句就有问题


这时候就应该用动态sql

上面的statement可以写成这样

	<select id="findUser" parameterType="user" resultType="user">
		SELECT * FROM USER  WHERE
		<!-- where自动将第一个and去掉 -->
		<where>
			<!-- 这里判断id的值是否为空,不为空就执行下面的语句,否则则不执行 -->
			<if test="id!=null and id!=''">
				and id=#{id}
			</if>
			<if test="sex!=null and sex!=''">
				and sex=#{sex}
			</if>
		</where>
	</select>


where标签可以自动判断if标签内容,才决定是否执行该if标签的内容




sql片段:可以将一些sql定义成一个片段,可以被其它statement引用。


Sql片段定义:

	<!-- sql片段
		用户查询的条件
		id:在namespace唯一的标示 -->
	<sql id="query_user">
		<!-- 这里判断id的值是否为空,不为空就执行下面的语句,否则则不执行 -->
		<if test="id!=null and id!=''">
			and id=#{id}
		</if>
		<if test="sex!=null and sex!=''">
			and sex=#{sex}
		</if>
	</sql>


Sql片段使用:

	<select id="findUser" parameterType="user" resultType="user">
		SELECT * FROM USER  WHERE
		
		<!-- where自动将第一个and去掉 -->
		<where>
			<!-- refid:指定sql片段的id,如果要引入其他命名空间的sql片段,需要在前边家namespace -->
			<include refid="query_user"></include>
		</where>
		
	</select>



foreach

需求 :传入多个id查询用户

SELECT * FROM USER  WHERE id=3 OR id=5 OR id=2


在User.java中定义一个数组属性

private int[] ids = {1,3,5};

UserMapper.xml

	<select id="findUser" parameterType="user" resultType="user">
		SELECT * FROM USER  WHERE
		<if test="ids!=null">
			<!-- 
				collection:一个数组
				item:遍历的每个对象
				open:开始遍历是拼接的sql
				separator:遍历的间隔符号
				close:结束遍历是拼接的sql
				
				要拼接的sql如下
				SELECT * FROM USER  WHERE id IN  (1,3,5)				
			 -->
			<foreach collection="ids" item="id" open="IN ("
				separator="," close=")">
				#{id}
			</foreach>
		</if>
	</select>









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值