<select id="getStudents" resultType="student" parameterType="map">
select * from mybatis_test.student
<where>
<choose>
<when test="id != null">
id = #{id}
</when>
<when test="name != null">
and name = #{name}
</when>
<otherwise>
and tid = #{tid}
</otherwise>
</choose>
</where>
</select>
解释:map对象中有三个属性:id,name,tid。
如果id不为空则匹配id,下面的name和tid都不匹配,
如果name不为空则匹配name,下面的id和tid都不匹配。
如果id和name都为空则执行otherwise的tid匹配。
- choose标签,when标签,otherwise标签组合起来就相当于java中的switch语句。
- 当满足其中一个when标签中的条件时,将不再执行其他的when标签和otherwise标签
- 当所有的when标签中的条件均未满足时,执行othewise标签
如果想不一定要执行otherwise,可以在里面套<if>
<select id="query" parameterType="com.ICEvidenceDocumentTemplateQueryDTO" resultMap="ICEvidenceDocumentTemplateResult">
<include refid="selectTemplate" />
<where>
<choose>
<when test="id_ != null">ID_ = #{id_, jdbcType=INTEGER}</when>
<when test="templateName != null and templateName != ''">
TEMPLATE_NAME=#{templateName, jdbcType=VARCHAR}
</when>
<otherwise>
<if test="templateNameDescription != null and templateNameDescription != ''"> and TEMPLATE_NAME like concat("%",#{templateNameDescription},"%")
or ID_ = #{templateNameDescription}
</if>
</otherwise>
</choose>
and ISDELETED = '0'
</where>
order by
ID_ asc
</select>
这样如果前面都为空,不符合,则最后的otherwise里面的if也为空时,则仅匹配外面ISDELETED = '0'的数据。