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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码