[英]JPA @IdClass - update
如果你有一個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(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
至於每個其他實體:您提供ID的實例:
EmployeePK pk = new EmployeePK(...);
Employee anemployee = em.find(Employee.class, pk);
然后要更新員工,就像處理其他任何實體一樣:您可以修改其字段,並且在事務提交時,新狀態將自動保留。 只要確保不更新名稱和出生日期即可:因為它們是PK的一部分,所以它們是不可變的。 這是不使用復合鍵,尤其是功能性復合鍵的許多良好原因之一。
使用自動生成的代理密鑰,一切將變得更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.