下面示例把原来写死的 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>里重复写。
