mybatis控制动态SQL拼接标签之choose标签

发布时间 2023-04-27 21:42:50作者: 红尘过客2022

mybatis控制动态SQL拼接标签之choose标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。

MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。

当choose中所有when的条件都不满则时,则执行 otherwise中的sql。

类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

if是与(and)的关系,而choose是或(or)的关系。

例如:有个资源管理界面,可能管理侧查询的是所有的agent资源,而从租户侧有需要查看的是所有的名下私有云资源。

<select id="getAllAgent" resultMap="com.wht.demo.dao.vo.AgentVo">     
	<choose>     
            <when test="isHis!=null and isHis!='' ">     
                   select 
						t.node_id as nodeId,
						t.host_name as hostName,
						t.address_ip as addressIp
					from 
					t_node_agent t 
					<where> 
						<if test='appId !=null and appId != "" '>
							and t.app_id= #{appId}  
						</if>
						<if test='osType!=null and osType!= "" '>
							and t.os_type= #{osType}  
						</if>
					</where>     
            </when>                     
            <otherwise>     
                   select 
						t.node_id as nodeId,
						t.host_name as hostName,
						t.address_ip as addressIp
					from 
					t_node_ec2 t 
					<where> 
						<if test='appId !=null and appId != "" '>
							and t.app_id= #{appId}  
						</if>
						<if test='osType!=null and osType!= "" '>
							and t.os_type= #{osType}  
						</if>
					</where>   
            </otherwise>     
     </choose>       
</select>