admin管理员组

文章数量:1134247

I’m just looking for some clarification on what is potentially quite a newbie question. I have a one-to-many relationship mapped as below (getters and setters not shown) - this is all okay and working fine under “normal” circumstances. I have a problem though…

With the lazy mapping the PurchaseOrder entity has an instance in memory that differs from the instance returned by the getter in the PurchaseOrderItem table. In other words PurchaseOrder.getItems().get(0).getPurchaseOrder() != PurchaseOrder in terms of the instance loaded into memory.

As previously mentioned this does not normally cause me any issues. However, if I have a property in the PurchaseOrder table that is changed via a UI and that property is subsequently used as part of a calculation in the PurchaseOrderItem referenced by its join column, then the join column is still referencing the other instance in memory with the incorrect property value.

The only way I can see to fix this is to change the fetch type on the relationship to EAGER in which case PurchaseOrder.getItems().get(0).getPurchaseOrder() == PurchaseOrder. However this seems like I’m fixing the issue at the expense of optimal data loading (imagine a very large list of Purchase Orders). Would anyone be able to shed some light on this behaviour? Am I doing it wrong? Is there a tried and tested way of achieving the goal I'm seeking?

PurchaseOrder Table

@OneToMany(mappedBy = "purchaseOrder", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<PurchaseOrderItem> items;

PurchaseOrderItem Table

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "purchase_order_id", foreignKey = @ForeignKey(name = "fk_purchase_order_item_on_purchase_order"))
private PurchaseOrder purchaseOrder;

本文标签: javaOneToMany Lazy vs Eager InstancesStack Overflow