简体   繁体   中英

How to use a Primary Key also as a Foreign Key reference with JPA and Hibernate?

I'd like to create a table where the primary key of an object should also serve as the foreign key for two @ManyToOne tables.

Is that possible without creating extra table columns both referencing and repeating the same primary key id?

Example:

@Entity
public class Person {
    @Id
    private int personId;

    @ManyToOne
    @JoinColumn(name="fk_address_id", foreignKey=@ForeignKey(name="fk_address"))
    private Address address;

    @ManyToOne
    @JoinColumn(name="fk_location_id", foreignKey=@ForeignKey(name="fk_location"))
    private Location location;
}

Problem: the @Id for Address and Location is always the same as @Id from Person . The mapping above will cause hibernate to generate 3 columns. id, fk_address, fk_location , where each of the columns have the same value (the id).

Question: is it possible to just having the primary key @Id for the person, and at the same time tell hibernate that this is the foreign key for some more @ManyToOne foreign key mappings, without these columns being created?

Assuming you have a one-to-one association between Person , PersonAddress , and PersonLocation , you need to use @MapsId JPA annotation because it is the best way to map a one-to-one table relationship .

I added an example on GitHub for this. Basically, you can map those associations like this:

@Entity(name = "Person")
public class Person  {

    @Id
    private Long personId;

    @OneToOne
    @MapsId
    @JoinColumn(name = "personId")
    private PersonAddress address;

    @OneToOne
    @MapsId
    @JoinColumn(name = "personId")
    private PersonLocation location;
}

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