Tarun
Tarun

Reputation: 3165

How two unidirectional mapping is different from bidirection mapping in Hibernate?

I am reading the book "Hibernate in Action" and finding difficulty to grasp the following concepts.

enter image description here

I am unable to understand why there are two different in-memory representation of same foreign key and why would hibernate detect two different changes to the foreign key when the following code is executed:

bid.setItem(item)
bids.add(bid)

The bid stored in the Item's bids collection and bid both refer to the same foreign key.

Upvotes: 0

Views: 50

Answers (1)

ieggel
ieggel

Reputation: 961

Item keeps a collection of Bids in memory and Bid keeps the Item in memory.

Item
------
Collection<Bid> bids;
Bid
------
Item item;
Bid bid = new Bid(...);   //bid object
Item item = getItemFromDb();  //item object

bid.setItem(item);
bids = item.getBids();
bids.add(bid);

In case you set an item for a bid, you also have to make sure to update the bids collection of the item object to keep everything in sync. Otherwise the bid object would have the item associated with it, however the item object would not have that bid in its collection, which means the item object would be out of sync.

Hope this helps!

Upvotes: 1

Related Questions