Composite Primary Key in JPA with @Embeddable annotation

Composite Primary Key is a table containg two or more columns Primary Keys. To represent them by entity in JPA, we can use the @Embeddable annotation. How is it in details? Let’s find out in this tutorial.

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

Composite Primary Key in JPA with @Embeddable annotation I will use Hibernate as JPA implementation so I will add Hibernate dependency as follows:

MySQL Connector:

Project Lombok:

Suppose in the database, you have a table student with the structure as follows:

As you can see, in this student table, I am defining it has 3 columns: id, code and name. It has a Composite Primary Key consisting of two Primary Keys: id and code.

To represent the structure of the student table in the entity, we first need to define an object containing the information of the Composite Primary Key using the @Embeddable annotation. The content of this class is as follows:

Note that this object must be implemented in the Serializable interface, and the equals() and hashCode() methods must be declared. This represents the uniqueness of the Composite Primary Key for each student record in the database.

Now, we can define the Student entity using the Composite Primary Key object as follows:

In above the Student entity, I declared the StudentId object with the @EmbeddedId annotation.@EmbeddedId annotation is used to declare a Primary Key property for complex objects containing multiple Primary Keys. For an entity that has declared a property with the @EmbeddedId annotation, then we cannot use the @Id annotation in that entity.

OK, so we have defined the Student entity with the Composite Primary Key. 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, I will use the EntityManager object to search the table student for records that have the Primary Key column with certain values. Id will now be the StudentId object.

Details as follows:

If in the database, I have the following data:

Composite Primary Key in JPA with @Embeddable annotation

then the results will look like this:

Composite Primary Key in JPA with @Embeddable annotation

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
5Tweet about this on Twitter
Share on LinkedIn

2 thoughts on “Composite Primary Key in JPA with @Embeddable annotation

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.