Search code examples
javahibernatemany-to-manyone-to-manymany-to-one

Hibernate One to Many and Many to One Relation


These two questions answered many of my questions, but I am still struggling to think about in real scenario!

Taking an example from the references. Assume I have one Order and Multiple Items associated with it. Now assume One Item can have one Returns but one Returns can have multiple Items.

What I understood is, Order to Items will be One to Many Relation. Since I need to get Order of an Item, I will create column 'order_fk' in Item table to get it.

//Order entity
@OneToMany
@JoinColumn(name = "order_fk")
private List<Items> items;

//item entity
@Column(name = "order_fk")
private Long orderId;

Return to Items is One to Many mapping. One Return can have multiple Items. But one Item can have only one return id

//Return entity
@OneToMany
@JoinColumn(name = "return_fk")
private List<Items> items;

//item entity
@Column(name = "return_fk")
private Long returnId;

Am I thinking in the right direction? Please make me understand this relations and uni/bi-directional relationships.

Overall, I should get Items for an Order. Get Orderid of given Item. Get Items of Returns and get returnId of given Item.

Reference:

  1. Difference Between One-to-Many, Many-to-One and Many-to-Many? Hibernate/JPA ManyToOne vs OneToMany

Solution

  • This should be the correct mapping of the entities (database tables and columns are ok)

    //Order entity
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private List<Items> items;
    
    //item entity
    @ManyToOne
    @Column(name = "order_fk")
    private Order order;
    
    //Return entity
    @OneToMany(mappedBy = "return")
    private List<Items> items;
    
    //item entity
    @ManyToOne
    @Column(name = "return_fk")
    private Return return;
    

    cascade = CascadeType.ALL in first mapping means whenever you save/update/delete an order, its items will also be saved/updated/deleted, so adjust it to your needs, on other mapping as well.

    Unidirectional relations mean only one side of the relation is aware of the other side. On your examples, if you removed items from Return entity you would have an unidirectional relation between Item and Return. With items present, you have a bidirectional relation.