一.if元素
相当于java的if,主要用来判断是否为空
<select id="ifsql" resultType="User">
select *
from user
where
<if test="id!=null">
id=#{id}
</if>
<if test="name!=null">
and name=#{name}
</if>
<if test="addr!=null">
and addr=#{addr}
</if>
</select>
二.choose....when.....otherwise.....元素
多重判断。
<select id="findRoles" 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>
三.trim,where set 元素
如果不知道where的条件十分存在,需要写 where 1=1,也可以写成<where></where>。
<select id="findOne" resultType="User">
select*
from user
<where>
id = #{id}
</where>
</select>
使用trim去掉and ,or等语法。
<select id="findOne" resultType="User">
select *
from user
<trim prefix="where" prefixOverrides="and">
and id = #{id}
</trim>
</select>
set用来只发送想要更新的字段,不用像hibernate一样全部发送造成冗余。set遇到都和可以自动去掉。
<update id="setsql">
update user
<set>
<if tes="roleName"!=null and roleName !=''">
roleName=#{roleName} ,
</if>
<if tes="age"!=null and age !=''">
age=#{age}
</if>
</set>
where id=131
</update>
四.foreache元素
foreach元素是一个循环语句,他的作用是遍历集合,支持数组,list,set接口的集合,对此提供遍历功能。往往用于in关键字。
- collection 配置的roleNoList是传递进来的参数名称,可以是一个数组,list,set等集合。
- item配置的是循环当中的元素
- index配置的是当前元素在集合的位置下标
- open和close配置的是以什么符号将这些集合元素包装起来。
- separator是各个元素的间隔符
<select id="fubdUserBySex" resultType="user">
slect * from t_role where role_no in
<foreach item="roleNo" index="index" collection="roleNoList" open="(" separator="," close="0">
#{roleNo}
</foreach>
</select>
五.用test的属性判断字符串
test用来判断真假,大部分用来判断空和非空,有时候需要判断字符串,数字,枚举等。
<select id="getRoleTest" parameterType="string" resultMap="roleResultMap">
select role_no,role_name,note from t_role
<if test=type='y'.toString>
where 1=1
</if>
</select>
六.bind元素
MySQL模糊查询,使用%和参数,但是Oracle没有,当使用bind就可以不适用数据库语言。
<select id ="findRole" parameterType="string" resultType="RoleBean">
<bind name="pattern" value="'%' + _parameter +'%'"/>
select *
from t_role
where role_name like #{pattern}
</select>