我有一个凭证 - POJO 映射到两个表。第一个映射分配实体名称“voucherA”并将 POJO 映射到 TableA。第二个映射使用“voucherB”作为实体名称,并将 POJO 映射到 TableB。
现在我还有一个映射到 TableC 的客户 POJO。此 POJO 引用列表中的凭证。
<list name="vouchers" table="TableC_vouchers">
<key column="pid"/>
<list-index column="position" base="0"/>
<!-- how to do that right -->
<many-to-many column="voucher_id" entity-name="voucherB"/>
</list>
如何正确映射从客户到凭证的多对多关联列表,以便如果客户 POJO 被持久化,则凭证实体将被持久化到 TableB(如果它们不存在),而不是 TableA?这可以做到吗?如果不是,那么有什么解决方法可以将客户使用的优惠券保留到 tableB 中? (表A仅包含可用的优惠券,不包含已使用的优惠券)
最佳答案
你的核心模型似乎是错误的。您的 Voucher
实体可能具有许多属性 - 在被 Customer
使用后,所有属性都会发生变化吗?我不信。然而,您在 A 和 B 表中复制它们,这意味着您的架构未标准化。
“可用”优惠券和“已使用”优惠券不是(或不应是)同一实体。相反,我建议您为 UsedVoucher
创建一个新实体,该实体将链接到多对一的 Voucher
和多对多的 Customer
- to-one 且仅包含 Voucher
的“已更改”属性(如果有)。所以,
Voucher(id, other attributes) // doesn't change from what you have now
Customer (id, other attributes) // doesn't change except for many-to-many; see below
UsedVoucher(id,
voucher, // what Voucher was used by that customer
customer, // what Customer has used that voucher
changed voucher attributes, // if any
additional attributes // if needed, such as date/time when voucher was used
)
如果您需要将其作为可维护的属性(property),您在客户
上的“多对多”将变为“一对多”(该客户使用的优惠券集合);否则可以通过查询轻松检索。
不过,在这种情况下,您无法从 Vouchers
表中进行物理删除(除非从未使用过相关的优惠券)。您必须执行逻辑删除。
关于java - 如何将多对多关联映射到映射到两个不同表的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662122/