Hibernate one to many mapping foreign key issue

寵の児 提交于 2020-05-30 08:23:23

问题


I am new to hibernate. Please help me in understanding this.

I have Department and Employee objects. Department is having employee collection with cascade type SAVE.I have created department object and employee object.lets say dept1 and emp1 respectively.When I save dept1 object(which is having emp1) ,it is saving dept1 and emp1 in department and employee tables with out foreign key.

Unless I am setting department(dept1) on emp1 , it is not saving foreign key. why should i manually set that? can't hibernate do that? Is there any reason for doing that?


回答1:


Because that's how the Hibernate documentation and the JPA spec tells you to do it. In a bidirectional association, there's an owner side, and an inverse side. The owner side is the one which doesn't have the mappedBy attribute. The inverse side is the one which has the mappedBy attribute.

In a bidirectional OneToMany, the owner side is always the many side (the one which has the foerign key).

Hibernate/JPA only cares about the owner side. If you don't initialize the owner side, it considers the association doesn't exist. Unless you really know what you're doing, a good rule of thumb is to initialize both sides of the association, to make your graph of entities coherent.



来源:https://stackoverflow.com/questions/11603085/hibernate-one-to-many-mapping-foreign-key-issue

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