如何使用复合键使用@IdClass注释

时间:2015-03-16 14:25:36

标签: jpa key entity eclipselink composite

有人可以使用带有@IdClass的复合键来共享一个使用Eclipse链接的Master-Detail模式的两个实体(JPA 2.1)的示例

1 个答案:

答案 0 :(得分:2)

以下是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);
     }
}

@IdClass(EmployeePK.class)
@Entity
public class Employee implements Serializable{

   @Id
   long empId;
   @Id
   @ManyToOne
   Department department;
   ...
}