简体   繁体   中英

hibernate 5, foreign key as primary key, unidirectional one to one

I have two entities:

First entity:

@Entity
@Table(name = "first")
public class First {

    @Id
    private Long id;

    // other properties
    // getters & setters

}

Second entity:

@Entity
@Table(name = "second")
public class Second {

    @OneToOne
    @JoinColumn(name = "first_id")
    private First first;

    // other properties
    // getters & setters

}

I want to make first field in Second entity will be primary key.

First first = new First()
repository.save(first);

(first.id = 1) must be

Second second = new Second()
second.setFirst(first); // as primary key
repository.save(second);

(second.first = first) must be

Use @MapsId and add an @Id field to the second entity:

@Entity
@Table(name = "second")
public class Second {

    @Id
    private Long Id;

    @MapsId
    @OneToOne
    @JoinColumn(name = "first_id")
    private First first;

    // other properties
    // getters & setters

}

See page 37 from JPA 2 spec :

Case (b): The dependent entity has a single primary key attribute corresponding to the relationship attribute. The primary key attribute is of the same basic type as the primary key of the parent entity. The MapsId annotation applied to the relationship attribute indicates that the primary key is mapped by the relationship attribute.

 @Entity public class MedicalHistory { @Id String id; // overriding not allowed ... // default join column name is overridden @MapsId @JoinColumn(name="FK") @OneToOne Person patient; ... } 

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