Composite Primary Key in JPA with @IdClass annotation

In the previous tutorial, I showed you how to represent a Composite Primary Key in JPA using the @Embeddable annotation. In addition to this, we also have a way to represent the Composite Primary Key in JPA which is using the @IdClass annotation. How is it in details? Let’s find out in this tutorial.

First, I also create a Maven project as an example:

Composite Primary Key in JPA with @IdClass annotation

I will use Hibernate as JPA implementation so I will add Hibernate dependency as follows:

MySQL Connector:

Project Lombok:

Table student:

To represent Composite Primary Key of student table, we first create a class containing the information of the two primary key columns. The difference from using @Embeddable annotation is that we do not need to use any annotations in this class. The content of this class is as follows:

Note that this object must also be implemented in the Serializable interface, and the equals() and hashCode() methods must be declared.

Next we will declare the Student entity using the @IdClass annotation with the StudentId object as follows:

As you can see, we will declare the @IdClass annotation with the value of the class name containing the Composite Primary Key definition. And another note is that in the Student entity declaration, we must declare the Primary Key columns with the annotation @Id.

That’s it! Now I will make an example to see how it works.

I will add the configuration file for JPA, persistence.xml, located in the /src/main/resources/META-INF directory with the following contents:

Next, I create a new class for example. In this class, we will use the EntityManager object to look up the table student, which records the primary key columns with certain values. Id will now be the StudentId object.

As follows:

If in the database, I have the following data:

Composite Primary Key in JPA with @IdClass annotation

then at runtime, the results will look like this:

Composite Primary Key in JPA with @IdClass annotation


Add Comment