Search code examples
jpakeyentityeclipselinkcomposite

How to use @IdClass annotation with composite key


Someone could please share an example of two entities working on a Master-Detail pattern for EclipseLink (JPA 2.1) using composite key with @IdClass


Solution

  • Here is the example from the documentation

        public class EmployeePK implements Serializable {
    
         private long empId;
         private long department;
    
         public EmployeePK() {
         }
    
         public long getEmpId() {
             return this.empId;
         }
    
         public void setEmpId(long empId) {
             this.empId = empId;
         }
    
         public long getDepartment() {
             return this.department;
         }
    
         public void setDepartment(long department) {
             this.department = department;
         }
    
         public int hashCode() {
             return (int)this.empId.hashCode();
         }
    
         public boolean equals(Object obj) {
             if (obj == this) return true;
             if (!(obj instanceof EmployeePK)) return false;
             EmployeePK pk = (EmployeePK) obj;
             return pk.empId.equals(this.empId) && pk.department.equals(this.department);
         }
    }
    

    and

    @IdClass(EmployeePK.class)
    @Entity
    public class Employee implements Serializable{
    
       @Id
       long empId;
       @Id
       @ManyToOne
       Department department;
       ...
    }