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