1、使用 where 标签
在 mybatis 的 xml 文件编写 SQL 语句已经是开发中最常使用的功能。但是通常我们看到的 SQL 都是下面这样:
这是正确的写法:
<select id="selectTableNameByEntity" parameterType="TableName" resultType="TableName">
select *
from tableName t
<where>
<if test="id != null and id != ''">
t.id = #{id}
</if>
<if test="userName != null and userName != ''">
and t.userName = #{userName}
</if>
<if test="password != null and password != ''">
and t.password = #{password}
</if>
</where>
</select>
可以发现,and 关键字总是放在 if 标签内部的前面,那么是否可以放在后面呢?例如:
<where>
<if test="id != null and id != ''">
t.id = #{id} and
</if>
<if test="userName != null and userName != ''">
t.user_name = #{userName} and
</if>
<if test="password != null and password != ''">
t.password = #{password}
</if>
</where>
答案是不可以!
原因:用 <where> 和 <if> 进行组合时,对 <if> 条件进行判断,一旦条件不成立时,<where> 标签会把对应的 and 关键字去掉(还有 or 关键字),因此就不会对整个 sql 语句产生影响。
但需要注意的是,and 关键字要放在每个 <if> 语句中的库表字段赋值的前面。因为,一旦判断不成功,<where> 只会把库表字段前面的 and 关键字去掉(或者 or 关键字)
如果 password 为空,此时得到的 sql 语句如下所示:
select * from tableName where t.user_name = 'Jungle' and t.user_name = 'admin' and
可以看到,sql 语句后面多了一个 and,这明显不符合 sql 的语法,执行会报错!
2、不使用 where 标签
那是否可以不使用 <where> 标签呢?答案是可以的。例如:
<select id="selectTableNameByEntity" parameterType="TableName" resultType="TableName">
select *
from tableName t
where
1 = 1
<if test="id != null and id != ''">
and t.id = #{id}
</if>
<if test="userName != null and userName != ''">
and t.userName = #{userName}
</if>
<if test="password != null and password != ''">
and t.password = #{password}
</if>
where
</select>
假设代码正常执行,字段都不为 null,那么可以得到 sql
select * from tableName where 1=1 t.user_name = 'Jungle' and t.user_name = 'admin' and password='123456'
注意,不适用 <where> 标签,1=1 是必须的,否则 sql 执行会出错:
select * from tableName where and t.user_name = 'Jungle' and t.user_name = 'admin' and password='123456'
where 后面紧跟一个 and,这是不符合 mysql 语法的。
或者你还可以将 1=1 置于代码后面,这样 and 需要放在赋值字段后面,例如:
<select id="selectTableNameByEntity" parameterType="TableName" resultType="TableName">
select *
from tableName t
where
<if test="id != null and id != ''">
t.id = #{id} and
</if>
<if test="userName != null and userName != ''">
t.userName = #{userName} and
</if>
<if test="password != null and password != ''">
t.password = #{password} and
</if>
1 = 1
where
</select>
执行得到 sql 如下:
select * from tableName where t.user_name = 'Jungle' and t.user_name = 'admin' and password='123456' and 1=1
但总的来说,在程序中出现 1=1 这样冗余的代码是不够优雅的,应该尽量使用 mybatis 提供的标签来编写代码。