Close

JPA - Composite key with @EmbeddedId involving @ManyToOne relationship

[Last Updated: Aug 8, 2017]

This example shows how to define a composite key by using @EmbeddedId having an identity which is derived from a @ManyToOne relationship.

This example is very similar to using @EmbeddedId with @OneToOne example, but with one difference; we will use @ManyToOne instead of @OneToOne. The ManyToOne relationship allows us to persist multiple target entity instances referencing the same source entity.

Example

@Entity
public class Task {
  @EmbeddedId
  private CompositeTaskId taskId;

  @MapsId("employeeKey")
  @ManyToOne
  private Employee employee;

  private String taskName;
  private Date date;

  public Task() {
  }

  public Task(CompositeTaskId taskId, Employee employee) {
      this.taskId = taskId;
      this.employee = employee;
  }
    .............
}
@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;
  }
    .............
}
@Embeddable
public class CompositeTaskId implements Serializable{
  private long employeeKey;
  private long taskId;

  public CompositeTaskId() {
  }

  public CompositeTaskId(long employeeId, long taskId) {
      this.employeeKey = 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, PRI, 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

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

      CompositeTaskId cti = new CompositeTaskId(1L, 100L);
      Task task = new Task(cti, e);
      task.setTaskName("Coding");
      task.setDate(new Date());

      CompositeTaskId cti2 = new CompositeTaskId(1L, 200L);
      Task task2 = new Task(cti2, e);
      task2.setTaskName("Refactoring");
      task2.setDate(new Date());

      em.getTransaction().begin();
      em.persist(e);
      em.persist(task);
      em.persist(task2);
      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 15:59:22.392, Coding, 1]
[200, 2017-08-08 15:59:22.392, Refactoring, 1]
-- Finding entity --
Task{taskId=CompositeTaskId{employeeKey=1, taskId=100}, employee=Employee{employeeId=1, name='Mike', dept='IT'}, taskName='Coding', date=2017-08-08 15:59:22.392}

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

@EmbeddedId with @ManyToOne Example Select All Download
  • embedded-id-with-many-to-one-relation
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Task.java
          • resources
            • META-INF

    See Also