You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hibernate XML映射如何在CommandLine实体中添加关联qtyStock属性

Hibernate XML映射实现方案

前置准备

首先在CommandLine实体类中新增qtyStock属性及对应的Getter/Setter方法:

// 新增属性
private Integer qtyStock;

// Getter
public Integer getQtyStock() {
    return qtyStock;
}

// Setter
public void setQtyStock(Integer qtyStock) {
    this.qtyStock = qtyStock;
}

核心映射配置(推荐使用formula计算属性)

直接在CommandLine对应的hbm.xml映射文件中添加qtyStock属性的配置,通过Hibernate的formula属性写原生SQL子查询自动计算库存值,无需额外配置实体关联:

<class name="你实际的包名.CommandLine" table="command_line">
    <!-- 其他原有属性映射保持不变 -->
    <id name="idCommandeLine" column="id_commande_line" type="java.lang.Long">
        <generator class="native"/>
    </id>
    <property name="idCommand" column="id_command"/>
    <property name="idItem" column="id_item"/>
    <property name="idStore" column="id_store"/>
    <property name="dateCommand" column="date_command"/>

    <!-- 新增qtyStock映射配置 -->
    <property name="qtyStock" type="java.lang.Integer" 
        formula="(
            SELECT COALESCE(s.qtyStock, 0)
            FROM Stock s
            INNER JOIN Store st ON st.idWarehouse = s.idWarehouse
            WHERE st.idStore = idStore
              AND s.idItem = idItem
        )"/>
</class>

配置说明

  • formula属性内写原生SQL语句,字段名需要和数据库表的实际字段名保持一致,语句中的idStore、idItem是当前CommandLine表的字段,Hibernate查询时会自动补全当前表的别名
  • 用COALESCE函数处理无库存记录时返回null的问题,默认返回0,也可以根据需求调整
  • 该属性为只读属性,Hibernate会在查询CommandLine对象时自动执行子查询填充值,遍历对象时可直接调用getQtyStock()获取库存

内容的提问来源于stack exchange,提问作者user2178964

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:27:01