欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 在Mybatis中写sql的常量应用

在Mybatis中写sql的常量应用

2025/5/7 1:24:36 来源:https://blog.csdn.net/Obscurede/article/details/147604830  浏览:    关键词:在Mybatis中写sql的常量应用

下面示例把原来写死的 1、2、3 都替换成了绑定好的常量,同时额外演示了如何把第五个状态也一起统计(如果你的 DTO 没有对应字段,也可删掉相应那一行)。

<!-- 1. 定义可复用的常量绑定 -->
<sql id="DeviceStatusConstants"><bind name="cntPendingDebugging"value="@org.jeecg.modules.test.constant.Constants@cntPendingDebugging"/><bind name="cntDebugging"value="@org.jeecg.modules.test.constant.Constants@cntDebugging"/><bind name="cntInspection"value="@org.jeecg.modules.test.constant.Constants@cntInspection"/><bind name="cntPendingAcceptance"value="@org.jeecg.modules.test.constant.Constants@cntPendingAcceptance"/><bind name="cntWaitingForDelivery"value="@org.jeecg.modules.test.constant.Constants@cntWaitingForDelivery"/>
</sql><!-- 2. 在查询中 include 并使用常量 -->
<select id="barChartData" resultType="org.jeecg.modules.test.dto.BarChartDataDTO"><include refid="DeviceStatusConstants"/>SELECTp.id,p.project_name AS projectName,-- 使用绑定后的常量,替代原来写死的数字SUM(CASE WHEN d.device_type = #{cntPendingDebugging} THEN 1 ELSE 0 END)       AS cntWaitDebugging,SUM(CASE WHEN d.device_type = #{cntDebugging} THEN 1 ELSE 0 END)             AS cntDebugging,SUM(CASE WHEN d.device_type = #{cntInspection} THEN 1 ELSE 0 END)            AS cntDebuggingDone,SUM(CASE WHEN d.device_type = #{cntPendingAcceptance} THEN 1 ELSE 0 END)     AS cntDebuggingInterrupted,SUM(CASE WHEN d.device_type = #{cntWaitingForDelivery} THEN 1 ELSE 0 END)    AS cntWaitingForDeliveryFROM v_projects pLEFT JOIN v_device_info dON p.id = d.project_idGROUP BY p.id
</select>
  • <bind> 可以把 OGNL 表达式(这里是访问类中 public static final 常量)的结果绑定到一个变量,后续直接用 #{变量名} 引用,避免反复写长长的全限定名 (java - MyBatis - dynamic variable - Stack Overflow)。
  • <sql>+<include> 则能把这些绑定统一管理,多处复用,无需在每个 <select> 里重复写。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词