1.对于从多个条件中选择一个的单条件查询的场景,利用分支嵌套就可以实现动态选择单条件:
在MyBatis的Mapper代理中,<choose>相当于switch,<when>相当于case
<select id="selByCondition2" resultMap="rm">
select *
from mybatis where
<choose>
<when test="status !=null">
STATUS=#{STATUS}
</when>
<when test="companyName !=null and companyName !=''">
company_name like #{companyName}
</when>
<when test="bracdName !=null and bracdName !=''">
bracd_name like #{bracdName}
</when>
<otherwise>1=1</otherwise>
</choose>
</select>
与多条件查询不同的是,SQL语句中只会有一个分支生效
当用户一个条件都不选时,可以在<otherwise>中写上1=1让语法成立,反之,若选择了条件则会返回正常结果
2.<select id="selByCondition" resultMap="rm">
select *
from mybatis
<where>
<if test="status !=null">
and STATUS=#{STATUS}
</if>
<if test="companyName !=null and companyName !=''">
and company_name like #{companyName}
</if>
<if test="bracdName !=null and bracdName !=''">
and bracd_name like #{bracdName}
</if>
</where>
</select>
<where>标签可以自动帮我们去掉and;另外一种写法是不使用<where>标签,通过where 1 = 1来实现