mybatis where 标签
我们经常在动态构造sql时,为防止注入或防止语句不当时会使用where 1=1
<select id="selectGroupByEmployeeNum" resultMap="BaseResultMap" parameterType="com.dao.impl.ZcChatGroup">
select
*
from
zc_chat_group
WHERE 1=1
<if test="id!=null">
id= #{id}
</if>
<if test="leaderNum!=null">
and leader_num = #{leaderNum}
</if>
<if test="groupType!=null">
and group_type = #{groupType}
</if>
</select>
但在使用where标签可以简化这条语句
<select id="selectGroupByEmployeeNum" resultMap="BaseResultMap" parameterType="com.dao.impl.ZcChatGroup">
select
*
from
zc_chat_group
<where>
<if test="id!=null">
id= #{id}
</if>
<if test="leaderNum!=null">
and leader_num = #{leaderNum}
</if>
<if test="groupType!=null">
and group_type = #{groupType}
</if>
</where>
</select>
这条sql执行时,如果id这个参数为null,则这条语句的执行结果为
select * from zc_chat_group where leader_num = ‘xx’ and group_type = ‘xx’
这个‘where’标签会知道如果它包含的标签中有返回值的话,它就会插入一个‘where’。此外,如果标签返回的内容是以AND 或OR开头的,则会把它去除掉。