JPA @EmbeddedId example

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, in previous article we have seen how compound primary keys can be generated using @IdClass annotation. This article gives JPA @EmbeddedId example i.e. another way of creating compound primary keys.

 

JPA @EmbeddedId example:

Consider Employee entity such that.

  • The primary key of Employee table is composed of two columns.
  • The columns are idEmployee and branchName
  • The combination of idEmployee and branchName collectively makes the primary key.

In database, Employee table is as depicted.

EmployeeEntity

For JPA @EmbeddedId example, we will use @EmbeddedId. This is what javadoc says about it.

Is applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable.

Let us directly look into JPA @EmbeddedId example.

Notice that instead of annotating two fields like previous example, We have created a field of type EmployeeId which acts like compound primary key.

Note that only difference in JPA @EmbeddedId example from previous post is this time it is annotated with @EmbeddedId. All other things remain same.

Now we can check this jpa @EmbeddedId example by trying to find an Employee with a specific branchName and idEmployee.

Data in Employee table is as below.

1 pune Prasad Kharkar 100000

Let us try to find entity using jpa code.

This find the employee from database and prints its information.

First name = Prasad Last Name = Kharkar salary = 100000

I hope this JPA @EmbeddedId example helped understand the concept of compound primary key in jpa using @EmbeddedId

References for further study :

Share Button

6 comments for “JPA @EmbeddedId example

  1. Nazmuddin
    October 4, 2015 at 1:01 pm

    It’s giving me an null pointer exception please help…

  2. Lucy
    September 21, 2016 at 3:52 pm

    How we can paging with EmbeddedId When We Using JPA Repository?

  3. vikram
    May 1, 2017 at 12:30 pm

    Can we create a constructor in Employee class as Employee(EmployeeID empid,String fName,String lName,int salary) ?

Leave a Reply

Your email address will not be published. Required fields are marked *