Mybatis SQL的动态问题(灵活去逗号,and,连接词)-trim篇
前言
在我们开发的时候,必不可免碰到复合SQL语句,然后就牵扯到有些参数为空,但又不想用判空来筛选数据,然后重复制造轮子,比如:灵活去逗号,and,连接词
1、trim标签
Mybatis具有实现动态SQL的能力,可以通过使用trim标签来拼凑SQL语句。
trim 在英语中有“点缀物”,修剪的意思。可以把‘’标签为一个装饰sql的标签。
标签说明
其基本格式如下:
<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>
-
prefix:
-
表示在trim包裹的SQL语句前面添加的指定内容。
-
suffix:
-
表示在trim包裹的SQL末尾添加指定内容
-
prefixOverrides:
-
表示去掉(覆盖)trim包裹的SQL的指定首部内容
-
suffixOverrides:
-
表示去掉(覆盖)trim包裹的SQL的指定尾部内容
mapper接口如下:
public User getUser
(@Param("LastName") String lastName,
@Param("age") Integer age,
@Param("phone") String phone);
常规的xml文件使用如下:
<select id="getUser" result="user">
select * from user_tab
where
last_name=#{lastName}
and
age=#{age}
and
phone=#{phone}
</select>
prefix 使用示例
<select id="getUser" resultType="user">
select * from user_tab
<trim prefix="where">
last_name=#{lastName} and age=#{age} and phone=#{phone}
</trim>
</select>
在动态生成sql的过程中,会将prefix前缀 拼接到 trim标签的外侧,最终得到的sql如下:
select * from user_tab
where //prefix="where"拼接出来的
last_name=#{lastName}
and
age=#{age}
and
phone=#{phone}
prefixOverrides 使用
有动态查询语句如下:
<select id="getUser" resultType="user">
select * from user_tab
<trim prefix="where"> //prefix="where"拼接出来的
<if test="lastName != null"> //当lastname为空的时候
last_name=#{lastName}
</if>
<if test="age != null">
and age=#{age}
</if>
<if test="phone != null">
and phone=#{phone}
</if>
</trim>
</select>
在动态sql的查询过程中,如果 lastName为null,所以第一个if不成立,里面的SQL语句不拼接,第二个if里面的and边紧跟在where后面了,语法错误。最终动态生成的sql如下:
select * from user_tab
where
and //多一个and
age = ?
and
phone = ?
为了解决这个问题,只要加上prefixOverride即可,表示把动态生成的sql中,trim标签内的首个“and”去掉。
<select id="getUser" resultType="user">
select * from user_tab
<trim prefix="where" prefixOverrides="and">//如果lastname为空去掉and的前缀
<if test="lastName != null">
last_name=#{lastName}
</if>
<if test="age != null">
and age=#{age}
</if>
<if test="phone != null">
and phone=#{phone}
</if>
</trim>
</select>
suffix使用示例
<select id="getUser" resultType="user">
select * from user_tab
<trim suffix="where id=#{id}">
update user_tab
set
last_name=#{lastName},
age=#{age},
phone=#{phone}
</trim>
</select>
在动态生成sql的过程中,mybatis 会将suffix 前缀 拼接到 trim标签所包含的sql的外侧,最终得到的sql如下:
select * from user_tab
where
id = ?
suffixOverrides的使用示例
如下的sql:
<update id="updateUser">
update user_tab
set
<if test="lastName != null">
last_name=#{lastName},
</if>
<if test="age != null">
age=#{age},
</if>
<if test="phone != null">
phone=#{phone}
</if>
where id = #{id}
</update>
在上述的动态sql中,若phone的值为null,则会导致生成的sql语句最后一个符号为“,”,导致生成的sql出错。
update user_tab
set ast_name=?, age=?,
为了避免此种情况,可使用trim标签中的suffixOverrides 将最后面的一个符号覆盖掉。即:
<update id="updateUser">
<trim suffix="where id=#{id}" suffixOverrides=",">
update user_tab
set
<if test="lastName != null">
last_name=#{lastName},
</if>
<if test="age != null">
age=#{age},
</if>
<if test="phone != null">
phone=#{phone}
</if>
</trim>
</update>
注意
trim中为空,
例如里面的所有if都不满足,trim会无效,
sql上面不会出现trim标签的内容