JPA - Composite key with @IdClass involving @OneToOne relationship (Derived Identity)

[Updated: Aug 17, 2017, Created: Aug 8, 2017]

We have already seen how to use @IdClass to map a composite key, but that use was limited to the identity of basic supported types.

In this example of @IdClass, we will see how to use an identity field of the target class (referenced class) of a @OneToOne relationship. The identity field of the target class is referred as 'derived identity field'.

The only difference, in this case (as compared to our last example of @IdClass; link given above) is, we will place one of our @Id annotations on the referenced @OneToOne field instead of some basic type field.

Let's see the example to understand how that works.

Example

@Entity
@IdClass(CompositeTaskId.class)
public class Task {
  @Id
  private long taskId;
  @Id
  @OneToOne
  private Employee employee;
  private String taskName;
  private Date date;

  public Task() {
  }

  public Task(Employee employee, long taskId) {
      this.employee = employee;
      this.taskId = taskId;
  }
    .............
}
@Entity
public class Employee {
  @Id
  private long employeeId;
  private String name;
  private String dept;

  public Employee() {
  }

  public Employee(long employeeId, String name, String dept) {
      this.employeeId = employeeId;
      this.name = name;
      this.dept = dept;
  }
    .............
}
public class CompositeTaskId implements Serializable {
  //the names of the both fields should be same as the @Id fields in source class
  //the type of 'taskId' field is same as of the basic @Id field defined in the Task entity
  private long taskId;
  //the type of 'employee' field is same as of the @Id field defined in Employee entity.
  private long employee;

  public CompositeTaskId() {
  }

  public CompositeTaskId(long employeeId, long taskId) {
      this.employee = employeeId;
      this.taskId = 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");
          nativeQuery(em, "SHOW COLUMNS from EMPLOYEE");
      } 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'
[EMPLOYEE, PUBLIC]
[TASK, PUBLIC]
'SHOW COLUMNS from TASK'
[TASKID, BIGINT(19), NO, PRI, NULL]
[DATE, TIMESTAMP(23), YES, , NULL]
[TASKNAME, VARCHAR(255), YES, , NULL]
[EMPLOYEE_EMPLOYEEID, BIGINT(19), NO, UNI, NULL]
'SHOW COLUMNS from EMPLOYEE'
[EMPLOYEEID, BIGINT(19), NO, PRI, NULL]
[DEPT, VARCHAR(255), YES, , NULL]
[NAME, VARCHAR(255), YES, , NULL]

H2 database SHOW statements

In above output, note that EMPLOYEE_EMPLOYEEID column is UNI (unique), which is important for a @OneToOne relationship. In case of @ManyToOne, this column is not unique (that's the only difference between @OneToMany and @ManyToOne) which allows to reference the multiple target entity instances for a same source entity. Check out our @OneToOne and @ManyToOne tutorials if not already familiar with the concepts.

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

      Employee e = new Employee(1L, "Mike", "IT");
      Task task = new Task(e, 100L);
      task.setTaskName("coding");
      task.setDate(new Date());

      em.getTransaction().begin();
      em.persist(e);
      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 EMPLOYEE");
      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(1, 100);
      Task task = em.find(Task.class, taskId);
      System.out.println(task);
      em.close();
  }
}

Output

-- Persisting entity --
-- Native query --
'Select * from EMPLOYEE'
[1, IT, Mike]
'Select * from Task'
[100, 2017-08-08 13:25:00.26, coding, 1]
-- Finding entity --
Task{taskId=100, employee=Employee{employeeId=1, name='Mike', dept='IT'}, taskName='coding', date=2017-08-08 13:25:00.26}

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.
  • JDK 1.8
  • Maven 3.3.9

@IdClass with @OneToOne Example Select All Download
  • id-class-with-one-to-one-relation
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • META-INF

See Also