Close

JPA - Composite Primary Key with @IdClass

[Last Updated: Aug 17, 2017]

A composite primary key consists of multiple primary key fields. Each primary key field must be one of the supported types for the primary key.

JPA specification requires a separate 'composite primary key class' having the primary key fields. The @Entity class must be linked to that class via @IdClass annotation.

public class MyCompositeKeyClass ....{
  //primary key fields
  ......
}
@Entity
@IdClass(MyCompositeKeyClass.class)
public static class MyEntity{
   ......
}

The @Entity class still needs to define the id fields (annotated with @Id) having the same names and types as of the 'composite primary key class'.

The 'composite primary key class' must implement Serializable and must implement equals and hasCode methods.

Example

@Entity
@IdClass(CompositeTaskId.class)
public class Task {
  @Id
  private int employeeId;
  @Id
  private int taskId;
  private String taskName;
  private Date date;

  public Task() {
  }

  public Task(int employeeId, int taskId) {
      this.employeeId = employeeId;
      this.taskId = taskId;
  }
    .............
}
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]

Note that there are two primary key columns (EMPLOYEEID and TASKID) which form a composite key.

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();

      Task task = new Task(5, 10);
      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-30 23:36:38.003, coding]
-- Finding entity --
Task{employeeId=5, taskId=10, taskName='coding', date=2017-07-30 23:36:38.003}

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 @IdClass Select All Download
  • composite-primary-key
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Task.java
          • resources
            • META-INF

    See Also