mybatis的标签
1. 用于where语句中,通过判断参数值来决定是否使用某个查询条件
2. 用于update语句中,判断某个字段是否更新
3. 在insert语句中,判断是否插入某个字段的值
select
< include refid = " userSql" />
from sys_user
< where>
1=1
< if test = " userName !=null and userName !=' ' " >
and user_name like concat('%',#{userName},'%')
if>
< if test = " userEmail !=null and userEmail !=' ' " >
and user_email=#{userEmail}
if>
where>
select>
< update id = " updateByIdSelective" parameterType = " SysUser" >
update sys_user
< set>
< if test = " userName!=null and userName !=' ' " >
user_name = #{userName},
if>
< if test = " userPassword!=null and userPassword !=' ' " >
user_password = #{userPassword},
if>
< if test = " userEmail!=null and userEmail!=' ' " >
user_email = #{userEmail},
if>
< if test = " userInfo!=null and userInfo !=' ' " >
user_info = #{userInfo},
if>
< if test = " headImg!=null" >
head_img = #{headImg},
if>
< if test = " createTime!=null" >
create_time = #{createTime},
if>
set>
< where>
id=#{id}
where>
update>
< insert id = " insertByIdIf" parameterType = " SysUser" >
insert into sys_user
(user_name,user_password,
< if test = " userEmail !=null and userEmail !=' ' " > user_email, if>
user_info,head_img,create_time)
values
(#{userName},#{userPassword},
< if test = " userEmail !=null and userEmail !=' ' " > #{userEmail}, if>
#{userInfo},#{headImg,jdbcType=BLOB},#{createTime,jdbcType=TIMESTAMP})
insert>
一个choose 中至少有一个when,有0个或1个otherwise
select
< include refid = " userSql" />
from sys_user
< where>
1=1
< choose>
< when test = " id !=null" >
and id=#{id}
when>
< when test = " userName !=null and userName !=' ' " >
and user_name =#{userName}
when>
< otherwise>
and 1=2
otherwise>
choose>
where>
select>
1. 如果该标签包含的元素中有返回值,就插入一个where
2. 如果where后面的字符串是以AND或者OR 开头的,就剔除
- 如果该标签包含的元素中有返回值,就插入一个set
- 如果set后面的字符串是以逗号结尾的,就将这个逗号剔除
- prefix:当trim元素包含内容时,会给内容增加prefix指定的前缀
- prefixOverrides:当trim元素包含内容时,会把内容中匹配的前缀字符串去掉
- suffix:当trim元素包含内容时,会给内容增加suffix指定的后缀
- suffixOverrides:当trim元素包含内容时,会给内容中匹配的后缀字符串去掉
where 和 set标签的功能都可以用trim标签来实现,并且在底层就是通过TrimSqlNode实现的 where标签对应的trim实现
< trim prefix = " WHERE" prefixOverrrides = " AND |OR " >
trim>
< trim prefix = " WHERE" prefixOverrrides = " ," >
trim>
name 为绑定到上下文的变量名
value 为OGNL表达式
< if test = " userName!=null and userName!=' ' " >
< bind name = " userNameLike" value = " ' %' +userName+' %' " />
and user_name like #{userNameLike}
if>
select
< include refid = " userSql" />
from sys_user
< where>
1=1
< if test = " userName !=null and userName !=' ' " >
< if test = " _databaseId==' mysql' " >
and user_name like concat('%',#{userName},'%')
if>
< if test = " _databaseId==' oracle' " >
and user_name like '%'||#{userName}||'%'
if>
if>
< if test = " userEmail !=null and userEmail !=' ' " >
and user_email=#{userEmail}
if>
where>
select>