Search code examples
javahibernateormone-to-onerelationships

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


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?


Solution

  • 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.