Don’t want to read? You can watch it here!

Solution:

You can use JPA’s @MapsId annotation to tell Hibernate that it shall use the foreign key of an associated entity as the primary key.

Let’s take a look at a simple example.

Each Book has a Manuscript, and each Manuscript belongs to 1 Book. The foreign key of the Book is also the primary key of the Manuscript.

Mapping the Book entity

There is nothing special about the mapping of the Book entity. It defines the primary key attribute id and tells Hibernate to use a sequence to generate the primary key values. It also specifies the title attribute as a simple String and a one-to-one association to the Manuscript entity.

Mapping the Manuscript entity

The mapping of the Manuscript entity is more complex but also not very complicated. It defines an id attribute as the primary key and a file attribute of type byte[].

The important part is the book attribute which defines the association between the Book and the Manuscript entity. The @OneToOne and the @JoinColumn annotations specify the association. The @MapsId annotation tells Hibernate to use the primary key value of the Book entity as the primary key value of the Manuscript entity.