myBatis中是不支持if-else的,想要是用if-else的话,可以使用choose代替。
choose,when,otherwise有点像Java中的switch.
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
if标签是与(and)的关系,而 choose 是或(or)的关系
一起来看一段代码
<select id="getAreaInfo" resultType="java.util.HashMap">
select prov_id "proId", pro_name "proName", area_id "cityId", area_desc "cityName"
from (
<choose>
<when test='provId=="111"'>
select p.prov_id, p.pro_name, a.area_id, a.area_desc, to_number(p.ord2) pro_ord ,a.ord area_ord
from dmcode_pub.dmcode_province p
left join dmcode_pub.dmcode_area a
on p.prov_id = a.prov_id
where a.is_valid = '1'
and p.s_n_mark is not null
and a.area_id != '999'
<if test='hasNanBei == "1"'>
<include refid="unionNorth"/>
<include refid="unionSouth"/>
</if>
<include refid="unionWhole"/>
</when>
<when test='provId=="112"'>
select p.prov_id, p.pro_name, a.area_id, a.area_desc, to_number(p.ord2) pro_ord ,a.ord area_ord
from dmcode_pub.dmcode_province p
left join dmcode_pub.dmcode_area a
on p.prov_id = a.prov_id
where a.is_valid = '1'
and p.s_n_mark='10'
and a.area_id != '999'
<include refid="unionNorth"/>
</when>
<when test='provId=="113"'>
select p.prov_id, p.pro_name, a.area_id, a.area_desc, to_number(p.ord2) pro_ord ,a.ord area_ord
from dmcode_pub.dmcode_province p
left join dmcode_pub.dmcode_area a
on p.prov_id = a.prov_id
where a.is_valid = '1'
and p.s_n_mark ='21'
and a.area_id != '999'
<include refid="unionSouth"/>
</when>
<otherwise>
select p.prov_id, p.pro_name, a.area_id, a.area_desc, to_number(p.ord2) pro_ord ,a.ord area_ord
from dmcode_pub.dmcode_province p
left join dmcode_pub.dmcode_area a
on p.prov_id = a.prov_id
where a.is_valid = '1'
and p.prov_id=#{provId}
<if test='areaId == "-1"'>
and a.area_id != '999'
</if>
<if test='areaId != "-1"'>
and a.area_id = #{areaId}
</if>
</otherwise>
</choose>
)
order by to_number(pro_ord) asc, to_number(area_ord) asc
</select>
choose 中包含了三个when一个otherwise
判断满足when中哪个条件,如果都不满足则执行otherwise