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来定义一个变量,就不用管数据库语言了,兼容性更强。