<where>
、<trim>
元素
在前两节的案例中,映射文件中编写的SQL后面都加入了“where1=1”的条件,是为了保证当条件不成立时拼接起来的SQL语句在执行时不会报错,即使得SQL不出现语法错误。那么在MyBatis中,有没有什么办法不用加入“1=1”这样的条件,也能使拼接后的SQL成立呢?针对这种情况,MyBatis提供了<where
>元素。
【示例】以之前的案例为例,将映射文件中的“where 1=1”条件删除,使用<where>
元素替换后的代码如下所示。
<!--<if><where>元素使用-->
<select id="findUserByNameAndJobs" parameterType="com.ssm.po.User" resultType="com.ssm.po.User">
select * from t_user
<where>
<if test="username !=null and username !=''">
and username like concat('%', #{
username},'%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs = #{
jobs}
</if>
</where>
</select>
上述配置代码中,使用<where>
元素对“where 1=1”条件进行了替换,<where>
元素会自动判断组合条件下拼装的SQL语句,只有<where>
元素内的条件成立时,才会在拼接SQL中加入where关键字,否则将不会添加;即使where之后的内容有多余的“AND”或“OR”,<where>
元素也会自动将它们去除。除了使用<where>
元素外,还可以通过<trim>
元素来定制需要的功能,上述代码可以修改为如下形式。
<!--<if>、<trim>元素使用-->
<select id="findUserByNameAndJobs" parameterType="com.ssm.po.User" resultType="com.ssm.po.User">
select * from t_user
<trim prefix="where" prefixOverrides="and">
<if test="username !=null and username !=''">
and username like concat('%', #{
username},'%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs = #{
jobs}
</if>
</trim>
</select>
上述配置代码中,同样使用<trim>
元素对“whee 1=1”条件进行了替换,<trim>
元素的作用是去除一些特殊的字符串,它的prefix属性代表的是语句的前缀(这里使用where来连接后面的SOL片段),而prefixOverrides属性代表的是需要去除的那些特殊字符串(这里定义了要去除SQL中的and),上面的写法和使用<where>
元素基本是等效的。