在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"/>
  SELECT
    p.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 cntWaitingForDelivery
  FROM v_projects p
  LEFT JOIN v_device_info d
    ON p.id = d.project_id
  GROUP BY p.id
</select>
  • <bind> 可以把 OGNL 表达式(这里是访问类中 public static final 常量)的结果绑定到一个变量,后续直接用 #{变量名} 引用,避免反复写长长的全限定名 (java - MyBatis - dynamic variable - Stack Overflow)。
  • <sql>+<include> 则能把这些绑定统一管理,多处复用,无需在每个 <select> 里重复写。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值