本文源码地址: https://github.com/nieandsun/NRSC-STUDY
1 set 标签
set标签的作用:在更新时,配合if标签使用
(1)可以去掉最后一个成立的if标签语句中的逗号,使update语句不会报错
(2)但是如果if都不成立时,整个set语句块会不生效,从而会导致sql语句会报错
<update id="updateByPrimaryKeySelective" parameterType="cn.nrsc.study.entity.TUser">
update t_user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="gender != null">
gender = #{gender,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
2 where 标签
where标签作用:在查询时,配合if标签使用
(1)可以去掉第一个成立的if标签语句中的and,使select语句不会报错
(2)如果if条件都不成立时,则整个where语句块都不生效,从而会查出所有数据
<select id="findTUserSelective" resultMap="BaseResultMap" parameterType="com.nrsc.mybatis.po.UserPo">
select
<include refid="Base_Column_List"/>
from t_user
<where>
<if test="username!=null">
and username = #{username}
</if>
<if test="salary!=null ">
and salary = #{salary}
</if>
</where>
</select>
3 trim标签
trim标签比set标签和where标签的功能更强大,它完全可以代替这两个标签。
trim标签有四个元素:
- prefix — 被trim包围的内容以prefix元素指定的内容开头
- suffix — 被trim包围的内容以suffix元素指定的内容结尾
- prefixOverrides — 去掉在trim包围的内容里的第一个该元素指定的内容
- suffixOverrides — 去掉在trim包围的内容里的最后一个该元素指定的内容
示例如下:
<insert id="insertSelective" parameterType="com.nrsc.mybatis.pojo.TUser">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="gender != null">
gender,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="gender != null">
#{gender,jdbcType=VARCHAR},
</if>
</trim>
</insert>
4 choose 、when 、otherwise
if用于但条件分支判断
choose 、when 、otherwise用于多条件分支判断
示例如下:
<select id="selectByRole" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_user
<choose>
<when test="role==1">
where username = "张三"
</when>
<when test="role == 2">
where salary = 1500;
</when>
<otherwise>
where gender = 'F'
</otherwise>
</choose>
</select>