Java JPA@IdClass-更新
如果你有一门像这样的课Java JPA@IdClass-更新,java,jpa,Java,Jpa,如果你有一门像这样的课 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
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);
}
}
及
如何进行更新查询
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 all对于每个其他实体:您给出一个ID的实例:
EmployeePK pk = new EmployeePK(...);
Employee anemployee = em.find(Employee.class, pk);
和更新员工一样,与任何其他实体一样:修改其字段,在事务提交时自动保持新状态。只需确保不更新姓名和出生日期:因为它们是PK的一部分,所以是不可变的。这是不使用复合键的许多好理由之一,尤其是功能复合键
使用自动生成的代理密钥,一切都会简单得多
EmployeePK pk = new EmployeePK(...);
Employee anemployee = em.find(Employee.class, pk);