mybatis动态sql,常用元素介绍

mybatis动态sql,常用元素介绍

if元素

<select id="findRole1" parameterType="string" resultMap="roleResultMap">
		select role_no, role_name, note from t_role where 1=1
		<if test="roleName != null and roleName !=''">
			and role_name like concat('%', #{roleName}, '%')
		</if>
</select>

当参数“roleName”参数不为空的时候,就执行对“roleName”的模糊查询的操作。这个是经常用到的标签,需要重点掌握

choose、when、otherwise

<select id="findRole2" parameterType="role" resultMap="roleResultMap">
		select role_no, role_name, note from t_role
		where 1=1
		<choose>
			<when test="roleNo != null and roleNo !=''">
				AND role_no = #{roleNo}
			</when>
			<when test="roleName != null and roleName !=''">
				AND role_name like concat('%', #{roleName}, '%')
			</when>
			<otherwise>
				AND note is not null
			</otherwise>
		</choose>
</select>

choose、when、otherwise相当于java代码中的switch、case、default功能的语句,也是比较常用的标签,需要重点掌握。

foreach元素

<select id="findRoleByNums" resultMap="roleResultMap">
		select role_no, role_name, note from t_role where role_no in
		<foreach item="roleNo" index="index" collection="roleNoList"
			open="(" separator="," close=")">
			#{roleNo}
		</foreach>
</select>

foreach 元素是一个循环语句,他的作用是编译集合,往往作用与SQL中的in关键字。

  • collection:配置的是传过来的参数名称,他可以是一个数组或者集合
  • open、close:是表示用什么符号将这些集合元素包装起来
  • separator:用什么符号间隔起来
  • index:这个就比较明显了,数据数据的下标
  • item:配置的是循环当中的元素
    使用foreach时,如果作用于in关键字,需要考虑SQL语句的长度,因为有的数据库对SQL语句的长度是有限制的

bing元素

<select id="findRole" parameterType="string" resultMap="roleResultMap">
        <bind name="pattern" value="'%'+_parameter+'%'"></bind>
        select role_no, role_name, note from t_role where role_name like #{pattern}
</select>

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文,这样更方便使用。在进行模糊查询的时候,我们mysql数据库,常常用到的是concat来连接数据库:concat(’%’,name,’%’),而oracle这是用“||”来连接,但是我们用bind来定义一个变量,就不用管数据库语言了,兼容性更强。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值