Home > Java > javaTutorial > How to Map Composite Keys in JPA and Hibernate using EmbeddedId or IdClass?

How to Map Composite Keys in JPA and Hibernate using EmbeddedId or IdClass?

Susan Sarandon
Release: 2024-12-03 05:22:16
Original
652 people have browsed it

How to Map Composite Keys in JPA and Hibernate using EmbeddedId or IdClass?

Mapping Composite Keys with JPA and Hibernate

Mapping composite keys in Java Persistence API (JPA) and Hibernate can be achieved using the EmbeddedId or IdClass annotations.

With IdClass

  1. Define a separate primary key class (e.g., TimePK) that encapsulates the composite key fields and their getters/setters.
  2. Annotate the entity with the @IdClass annotation, specifying the primary key class.

With EmbeddedId

  1. Similarly, define a separate primary key class (e.g., TimePK).
  2. Annotate the primary key class with the @Embeddable annotation.
  3. Annotate the entity with the @EmbeddedId annotation and specify the primary key class.

Differences

  • Semantic: EmbeddedId suggests that the composite key has a specific meaning, while IdClass is more suitable when the combination of fields is simply a unique identifier.
  • Query Syntax: With EmbeddedId, the primary key fields are accessed through the embedded primary key class, while with IdClass the fields can be accessed directly.

References

  • JPA 1.0 Specification: Section 2.1.4, 9.1.14, and 9.1.15

The above is the detailed content of How to Map Composite Keys in JPA and Hibernate using EmbeddedId or IdClass?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template