if标签
<select id="findUserByName" parameterType="string" resultType="com.yunxiang.mybatis.pojo.User">
select * from user
<where>
<if test="_parameter != null and _parameter !='' ">
<!--模糊查询-->
name like "%"#{name}"%"
</if>
</where>
注:if标签用于判断查询,“test"属性表示要进行判断的条件。在当"parameterType"属性为"java.lang.String"类型时,只能使用”_parameter"来接受参数值,否则会报错。
where标签
<select id="findUserByName" parameterType="map" resultType="com.yunxiang.mybatis.pojo.User">
select * from user
<where>
<if test="sex != null and sex != '' ">
sex = #{sex}
</if>
<if test="name != null and name != '' ">
and name like "%"#{name}"%"
</if>
</where>
</select>
注:where标签用于在SQL语句中生成关键字"where",并且他可以自动去掉满足条件后的第一个"or"或者"and"。即在本例中,当"sex"不满足条件后,就会去掉"name"中的"and"。
choose标签
<select id="findUserByName" parameterType="map" resultType="com.yunxiang.mybatis.pojo.User">
select * from user
<where>
<choose>
<when test=" _parameter != null and _parameter !='' ">
name like "%"#{name}"%"
</when>
<otherwise>1=1</otherwise>
</choose>
</where>
</select>
注:choose标签可以进行原则判断,即当"_parameter"满足条件时,就将"“标签中的SQL语句添加到整个SQL语句中;当”_parameter"不满足条件时,就将""标签中的SQL语句添加到整个SQL语句中。
set标签
<update id="updateUser" parameterType="com.yunxiang.mybatis.pojo.User">
update user
<set>
<if test=" name != null and name != '' ">
name = #{name},
</if>
<if test=" sex != null and sex != '' ">
sex = #{sex},
</if>
<if test=" brithday != null and brithday != '' ">
brithday = #{brithday},
</if>
<if test=" address != null and address != '' ">
address = #{address},
</if>
</set>
where id = #{id}
</update>
注:set标签用于数据更新操作,并且他会自动去掉最后一个","。
foreach标签
SQL语句:“select * from user where (id =1 or id = 9 or id = 10)”
<select id="findUserListById" parameterType="java.util.List" resultType="com.yunxiang.mybatis.pojo.User">
select * from user
<where>
<if test="list != null">
<foreach collection="list" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</if>
</where>
</select>
注:foreach标签可以循环集合中的变量。"collection"表示用于接受的集合;"item"表示实在一个变量,用于取集合中的值;"open"表示循环以什么开头;"close"表示循环以什么结尾;"separator"表示名称循环时,中间使用什么东西拼接。
trim标签
trim标签可以替代where标签或set标签等
<select id="findUserByName" parameterType="map" resultType="com.yunxiang.mybatis.pojo.User">
select * from user
<trim prefix="where" prefixOverrides="and|or">
<if test="sex != null and sex != '' ">
or sex = #{sex}
</if>
<if test="name != null and name != '' ">
or name like "%"#{name}"%"
</if>
</trim>
</select>
注:"prefix"属性表示使用哪种标签,"prefixOverrides"属性表示忽略开始的什么内容,"suffixOverrides"表示忽略结尾的什么内容。
SQL片段
mybatis中可将重复的sql提取出来,定义成一个SQL片段,在使用时,使用时通过"<include>"标签引用定义的SQL片段就可以达到sql重用的目的。
<!--SQL片段的定义,id是SQL片段的唯一标识,
使用时,可以引用该id来使用该SQL片段-->
<sql id="user_col">
id,name,brithday,sex,address
</sql>
<!--SQL片段的使用-->
<select id="findUserById" parameterType="int" resultType="com.yunxiang.mybatis.pojo.User">
select <include refid="user_col"></include> from user where id = #{id}
</select>
注:如果SQL片段定义在不同的xml文件中,在使用时要加上该SQL片段定义的namespace名,即" "