Hibernate One to Many and Many to One Relation

回眸只為那壹抹淺笑 提交于 2019-12-11 17:52:01

问题


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

回答1:


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.




回答2:


I think you should use OneToMany in another way:

// Order entity
@OneToMany(mappedBy = "columnInItemsPointingAtOrders")
private List<Items> items;

Please check the docs: http://docs.oracle.com/javaee/6/api/javax/persistence/OneToMany.html.

And one more thing - you are not geting the IDs but entities:

//item entity
@Column(name = "order_fk")
private Order order;



回答3:


I'm also new to this subject. What helped me to understand the relations is drawing the EER diagram and then synchronizing it to the test DB and experimenting. This does not answer your question but may give a direction.



来源:https://stackoverflow.com/questions/27354583/hibernate-one-to-many-and-many-to-one-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!