简体   繁体   中英

Unidirectional one-to-one relationship

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;
}

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM