Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self Join relationship with JPA

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>
like image 313
javing Avatar asked Dec 27 '25 16:12

javing


1 Answers

I think this should do the trick:

@OneToOne(optional = true)
@JoinColumn(name = "SoulmateId")
private Person soulmate;
like image 143
K.C. Avatar answered Dec 30 '25 05:12

K.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!