membersound
membersound

Reputation: 86905

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?

Upvotes: 4

Views: 6463

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154090

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

Upvotes: 8

Related Questions