Close

JPA - Composite Primary Key with @EmbeddedId

[Last Updated: Aug 17, 2017]

Alternative to using @IdClass, @EmbeddedId is another way to add composite primary key in @Entity class.

In this case the 'composite primary key class' is embeddable i.e. annotated with @Embeddable

This is cleaner than using @IdClass as we don't have to repeat the same id fields at two places. It is also a more intuitive way to map a primary key using object composition.

Example

@Entity
public class Task {
  @EmbeddedId
  private CompositeTaskId taskId;
  private String taskName;
  private Date date;

  public Task() {
  }

  public Task(CompositeTaskId taskId) {
      this.taskId = taskId;
  }
    .............
}
@Embeddable
public class CompositeTaskId implements Serializable {
  private int employeeId;
  private int taskId;

  public CompositeTaskId() {
  }

  public CompositeTaskId(int employeeId, int taskId) {
      this.employeeId = employeeId;
      this.taskId = taskId;
  }

  @Override
  public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      CompositeTaskId taskId1 = (CompositeTaskId) o;
      if (employeeId != taskId1.employeeId) return false;
      return taskId == taskId1.taskId;
  }

  @Override
  public int hashCode() {
      return Objects.hash(employeeId, taskId);
  }
    .............
}

Main class showing table mappings

public class ExampleMain {

  public static void main(String[] args) {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      try {
          EntityManager em = emf.createEntityManager();
          nativeQuery(em, "SHOW TABLES");
          nativeQuery(em, "SHOW COLUMNS from TASK");
      } finally {
          emf.close();
      }
  }

  public static void nativeQuery(EntityManager em, String s) {
      System.out.printf("'%s'%n", s);
      Query query = em.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
  }
}

Output

'SHOW TABLES'
[TASK, PUBLIC]
'SHOW COLUMNS from TASK'
[EMPLOYEEID, INTEGER(10), NO, PRI, NULL]
[TASKID, INTEGER(10), NO, PRI, NULL]
[DATE, TIMESTAMP(23), YES, , NULL]
[TASKNAME, VARCHAR(255), YES, , NULL]

Persisting and loading data

public class ExampleMain2 {

  public static void main(String[] args) throws Exception {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      try {
          persistEntity(emf);
          runNativeQuery(emf);
          findEntityById(emf);
      } finally {
          emf.close();
      }
  }

  private static void persistEntity(EntityManagerFactory emf) throws Exception {
      System.out.println("-- Persisting entity --");
      EntityManager em = emf.createEntityManager();

      CompositeTaskId taskId = new CompositeTaskId(5, 10);
      Task task = new Task(taskId);
      task.setTaskName("coding");
      task.setDate(new Date());

      em.getTransaction().begin();
      em.persist(task);
      em.getTransaction().commit();
      em.close();
  }

  private static void runNativeQuery(EntityManagerFactory emf) {
      System.out.println("-- Native query --");
      EntityManager em = emf.createEntityManager();
      ExampleMain.nativeQuery(em, "Select * from Task");
  }

  private static void findEntityById(EntityManagerFactory emf) {
      System.out.println("-- Finding entity --");
      EntityManager em = emf.createEntityManager();
      CompositeTaskId taskId = new CompositeTaskId(5, 10);
      Task task = em.find(Task.class, taskId);
      System.out.println(task);
      em.close();
  }
}

Output

-- Persisting entity --
-- Native query --
'Select * from Task'
[5, 10, 2017-07-31 00:02:56.435, coding]
-- Finding entity --
Task{taskId=CompositeTaskId{employeeId=5, taskId=10}, taskName='coding', date=2017-07-31 00:02:56.435}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.10.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

JPA Composite Primary Key using @EmbeddedId Select All Download
  • embeddable-composite-primary-key
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Task.java
          • resources
            • META-INF

    See Also