2012-12-04 62 views
0

如果你有一個像JPA @IdClass - 更新

public class EmployeePK implements Serializable { 

private String empName; 
private Date birthDay; 

public EmployeePK() { 
} 

public String getName() { 
    return this.empName; 
} 

public void setName(String name) { 
    this.empName = name; 
} 

public Date getBirthDay() { 
    return this.birthDay; 
} 

public void setBirthDay(Date date) { 
    this.birthDay = date; 
} 

public int hashCode() { 
    return (int)this.empName.hashCode(); 
} 

public boolean equals(Object obj) { 
    if (obj == this) return true; 
    if (!(obj instanceof EmployeePK)) return false; 
    EmployeePK pk = (EmployeePK) obj; 
    return pk.birthDay.equals(this.birthDay) && pk.empName.equals(this.empName); 
} 

一個IdClass}

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

    @Id String empName; 
    @Id Date birthDay; 
    ... 

    public Employee (String empName, Date birthDay){ 
    this.empName= empName; 
    this.birthDay= birthDay; 
} 
... 
} 

你如何更新查詢?

EntityManagerFactory emf = Persistence 
      .createEntityManagerFactory("JPA_Compositekey"); 
    EntityManager em = emf.createEntityManager(); 
    try { 
     em.getTransaction().begin(); 
     Employee anemployee = em.find(**WHAT DO YOU FILL HERE **) 
... 

或者我必須使用PK類中的對象,以及如果您只有一個需要更新的人,該怎麼辦。

THX所有

回答

1

至於所有其他實體:你給的ID的一個實例:

EmployeePK pk = new EmployeePK(...); 
Employee anemployee = em.find(Employee.class, pk); 

,並更新公司員工,那麼就像任何其他實體:你修改它的領域,並且在事務提交時新的狀態會自動保持。只要確保不更新名稱和出生日期:因爲它們是PK的一部分,它們是不可變的。這是不使用組合鍵的許多好理由之一,尤其是功能組合鍵。

使用自動生成的代理鍵,一切都會容易得多。