OneToMany | Uni directional | (Non Optional) - gauravsk89/hibernate GitHub Wiki

Non-Optional Uni-directional OneToMany

Scenario:

In Online bidding system an item can have 0...n bids associated to it. And in this case association is kept as Unidirectional, but in real life in most cases it would be bi-directional (we may want to navigate to the item a bid belongs to).

Since this relation is not a Optional one, so on database FK is used to relate two tables (instead of creating a third join table).

BIDS table has a FK pointing to PK of ITEM table.

ITEM
	ID			(PK)
	NAME			NOT NULL
	INITIAL_AMOUNT		NOT NULL
	SELLER_ID		NOT NULL

BIDS
	ID			(PK)
	AMOUNT			NOT NULL
	ITEM_ID			(FK)

Entities:

Item entity has a collection reference to Bids

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ITEM_ID", nullable = false)
private Set<Bid> bids;

Since this is uni-directional association, so Bids entity has no reference back to Item class. But since an entity should be exact replica of respective table, so Bids entity needs to have a field corresponding to ITEM_ID column (FK) in BIDS table.

This reference is just a primitive holding the value of ITEM_ID, *** please note that it is not a entity reference to ITEM entity.

@Column(name = "ITEM_ID")
private Long itemId; 

A convenience method has been added in Item entity to update the association between the two entities.

public void addOrUpdateBids(Bid bid){
    if(this.bids == null){
        this.bids = new HashSet<>();
    }
    bid.setItemId(this.getItemId());
    this.getBids().add(bid);
} 

Persistence Logic:

@Override
@Transactional
public Item addBidToItem(BidDTO bidDTO) {

    Item item = itemsRepository.findOne(bidDTO.getItemId());

    Bid bid = Bid.builder()
                .bidAmount(bidDTO.getAmount())
                .itemId(item.getItemId())
                .build();

    item.addOrUpdateBids(bid);
    itemsRepository.save(item);

    return item;
}
⚠️ **GitHub.com Fallback** ⚠️