Self Join JPA

I want to create a Person table using JPA, it is a requirement that a Person has a field of type Person to represent a relative. A person can have a relative (another person), but not necessarily.

I am really confused about how to do my mappings. I'm not sure if the keyword can help me here.

I would like to understand what the best approach would be. This is what I did, but I think it is wrong. Can someone help me fix this and also explain to me how this should work?

Annotated version

   //DEFINE OneToOne Relationships (SELF JOIN-No mandatory)
    @Entity class Person {
         private long identificator;
         private String name;
         @OneToOne(targetEntity=Person.class mappedby="this")
         private Person soulmate;


Version using deployment descriptor

          <entityclass = "packgagename.Person">
                <id name="identificator"/>  
                <column name="name"/>
                <one-to-one name="soulmate" targetEntity="packgagename.Person" mappedby="this"/>                



source to share

1 answer

I think this should do the trick:

@OneToOne(optional = true)
@JoinColumn(name = "SoulmateId")
private Person soulmate;




All Articles