I want to create a table Person using JPA, it is a requirement that Person should have a field of type Person, to represent a soulmate. Person can have a soulmate(another person) but is no mandatory.
I am getting really confused in how to do my mappings. I am not sure if can the keyword this help me here.
I would like to understand what would be the best approach. This is what i did, but i think is not correct. Can someone help me correct it and also explain me how it this relationship should work?
Version using annotations
//DEFINE OneToOne Relationships (SELF JOIN-No mandatory)
@Entity class Person {
@Id
private long identificator;
private String name;
@OneToOne(targetEntity=Person.class mappedby="this")
private Person soulmate;
}
Version using deployment descriptor
<persistence-unit-metadata>
<entity-mappings>
<entityclass = “packgagename.Person”>
<attributes>
<id name="identificator"/>
<column name="name"/>
<one-to-one name="soulmate" targetEntity="packgagename.Person" mappedby="this"/>
</attributes>
</entityclass>
</persistence-unit-metadata>
I think this should do the trick:
@OneToOne(optional = true)
@JoinColumn(name = "SoulmateId")
private Person soulmate;