MyBatis动态SQL:where

如果我们将STATE=’ACTIVE’也设置成动态条件,看看会发生什么
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.fkit.mapper.EmployeeMapper">
    <select id="selectEmployeeByIdLike" resultType="org.fkit.domain.Employee">
        SELECT * FROM tb_employee WHERE
        <!-- 可选条件,如果传入参数有ID属性,则加上ID查询条件 -->
        <if test="state != null">
         STATE=#{state}
        </if>
        <if test="id != null">
         AND ID=#{id}
        </if>
    </select>
</mapper>
传入:
params.put("state", "ACTIVE");

输出:

当未传入任何参数时:

也就是说,如果没有参入state参数,会导致执行失败,这个问题不能简单的用条件语句来解决.MyBatis有一个简单的处理方法,只要简单的修改就能得到想要的效果
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.fkit.mapper.EmployeeMapper">
    <select id="selectEmployeeByIdLike" resultType="org.fkit.domain.Employee">
        SELECT * FROM tb_employee
        <where>
            <if test="state != null">
             STATE=#{state}
            </if>
            <if test="id != null">
             AND ID=#{id}
            </if>
            <if test="loginname != null and password != null">
             AND LOGINNAME=#{loginname} AND PASSWORD=#{password}
            </if>
        </where>
    </select>
</mapper>
where元素知道只有在一个以上的if条件有值的情况下才去插入WHERE子句.而且,若最后的内容是AND或OR,这WHERE元素也知道如何将他们去除
不设置params:
id=2
可见在使用ID但没有传入STATE时,MyBatis自动过滤了ID前面的AND关键字