Unidirectional one-to-one relationship

3.7k views Asked by At

How do I achieve a unidirectional one to one relationship for Person and PersonData?

@Entity
public class Person  {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    // @OneToOne...?
    // ...?
    private PersonData data;
}

@Entity
public class PersonData {
    @Id
    private long personId;
}
3

There are 3 answers

0
Elias Garcia On

Using the @OneToOne annotation with the @JoinColumn annotation to specify the primary key of the other entity:

@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="personId")
private PersonData data;
6
Abhilekh Singh On

You can use @PrimaryKeyJoinColumn to have shared primary key in PersonData Table.

@Entity
public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToOne(cascade = CascadeType.PERSIST, mappedBy = "personId")
    @PrimaryKeyJoinColumn
    private PersonData data;

}

@Entity
public class PersonData implements Serializable {

    @Id
    @OneToOne(targetEntity = Person.class)
    private Long personId;
}

For more details:

https://github.com/abhilekhsingh041992/spring-boot-samples/blob/master/jpa/src/main/java/example/springboot/jpa/domain/Person.java

https://github.com/abhilekhsingh041992/spring-boot-samples/blob/master/jpa/src/main/java/example/springboot/jpa/domain/PersonData.java

0
Newton Karani On

Add Person as targetEntity to @OneToOne in PersonData :

@OneToOne(targetEntity = Person.class)
private Person person;