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

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>
posted @   红尘过客2022  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示