问题
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