How to identify the mapped/owned sides of a self-referencing one-to-one relationship in Hibernate?

六月ゝ 毕业季﹏ 提交于 2019-12-11 09:56:43

问题


My Hibernate schema has a Port entity. Each Port should have zero or one connections to another Port so there is a "connectedPort" field referencing the same entity:

public class Port {
    // ...
    @OneToOne
    @JoinColumn
    private Port connectedPort;
    // ...
}

But normally for a @OneToOne there would be an "owned" side of the relationship and a "mapped" side of the relationship - is this also the case here - and if so, how and why?


回答1:


From the OneToOne API doc:

If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side.

So, either your connectedPort has no relationship to its reverse connected port and the holder of the field connectedPort has the foreign key, or the relationship is bi-directional and you have to specify who holds the foreign key using mappedBy.

Edit As I assume from your code snippet your connected ports have no knowledge of who is connected to them, so your Port holding the knowledge to whom they are connected hold the foreign key and are the owning side of this relationship.



来源:https://stackoverflow.com/questions/28558591/how-to-identify-the-mapped-owned-sides-of-a-self-referencing-one-to-one-relation

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