menu

Composite Primary Key

A Composite Primary Key is a combination of more than one columns that forms a primary key. When a database table contains a primary key, which is a combination of two or more columns, it is known as a composite primary key or a composite key.

In JPA, we have two options to define the composite keys:

1. @IdClass annotations.

2. @EmbeddedId annotations.

Rules for define a composite key class:

  • The composite primary key class must be public.

  • It must have a no-arg constructor.

  • It must be Serializable.

  • It must define getters and setters method.

SQL query for create table 'student_course_info'

img not found

@IdClass Annotation

Let's say we have a table called 'student_course_info' and it has two columns, 'student_id' and 'course', that form the composite key. Now we have to map it in JPA. As per the JPA specification, let's create an CompositKeyIdClass class with these primary key fields:

Next let's associate the CompositKeyIdClass class with the entity StudentCourseInfo. In order to do that, we need to annotate the entity with the @IdClass annotation. We must also declare the fields from the CompositKeyIdClass class in the entity StudentCourseInfo and annotate them with @Id:

@EmbeddedId Annotation

@EmbeddedId is an alternative to the @IdClass annotation. Let's consider same example where we have to persist some information of a StudentCourseInfo, with student_id and course as the primary key fields.

In this case, the primary key class, CompositKeyEmbeddable, must be annotated with @Embeddable.

Then we need to embed this class in the StudentCourseInfo entity using @EmbeddedId.

Source Code

Project Structure

img not found

pom.xml

Main class

Controller class

Bean class for @IdClass

Bean class for @EmbeddedId

Entitiy class for @IdClass

Entitiy class for @EmbeddedId

DAO class

application.properties