MyBatis的动态SQL

动态SQL的元素

1.if

在我们的SQL语句中,查询条件的值如果为空,可能会导致查询结果错误
为了避免这种错误的发生,我们使用了if判断.

	<select id="getUserList" resultMap="userList" >
	  		select * from smbms_user		where 1=1
	  			 <if test="userRole!=null">
		  		 	and u.userRole=#{userRole} 
		  		 </if>
		  		 <if test="userName!=null and userName!=''">
		  			and u.userName like CONCAT('%',#{userName},'%')
		  		 </if>	  		
	  	</select>

2.where

select * from smbms_user
	  		<where>
	  			  <if test="userRole!=null">
		  		 	and u.userRole=#{userRole} 
		  		 </if>
		  		 <if test="userName!=null and userName!=''">
		  			and u.userName like CONCAT('%',#{userName},'%')
		  		 </if>
	  		</where>

这里的where写法不推荐大家使用,相比之下,上面if里面写了一个where 1=1 之后再到后面加入if的判断结果出来较为好用

MyBatis入参为数组类型的foreach迭代

<select id="getUserByRoleId_foreach_array" resultMap="userArrayByRole">
			select * from smbms_user where userRole in
			<foreach collection="array" item="roleIds" open="(" separator="," close=")">
				#{roleIds}
			</foreach>
		</select>
		<resultMap type="cn.smbms.pojo.User" id="userArrayByRole">
			<result property="userCode" column="userCode"/>
	  		<result property="userName" column="userName"/>
		</resultMap>
item:表示集合中每一个元素进行的迭代时的别名
index:指定一个名称,用于标识在迭代过程中,每次迭代到的位置
open:表示该语句以什么开始
separator:表示在每次迭代之间以什么符号作为分隔符
close:表示该语句以什么结束
collection:最关键并最容易出错的属性,
	若入参为单参数且参数类型为List的时候,collection属性值为list,
	若入参为单参数且参数类型为数组的时候,collection属性值为array,
	若入参为多参数,collection属性值为Map,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值