简体   繁体   English

JPA @IdClass-更新

[英]JPA @IdClass - update

If you have a IdClass like 如果你有一个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);
 }

} }

and

@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;
}
...
}

how do you make an update query? 您如何进行更新查询?

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

Or must I use a object from the PK class and what to do if you have a just a person that you need to update. 还是我必须使用PK类中的对象以及如果您只有一个需要更新的人该怎么办。

Thx all 全部Thx

As for every other entity: you give an instance of the ID: 至于每个其他实体:您提供ID的实例:

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

And to update the employee, then just as with any other entity: you modify its fields, and the new state is automatically persisted when the transaction commits. 然后要更新员工,就像处理其他任何实体一样:您可以修改其字段,并且在事务提交时,新状态将自动保留。 Just make sure not to update the name and the birth date: as they're part of the PK, they are immutable. 只要确保不更新名称和出生日期即可:因为它们是PK的一部分,所以它们是不可变的。 That's one of the many good reasons not to use composite keys, especially functional composite keys. 这是不使用复合键,尤其是功能性复合键的许多良好原因之一。

Everything would be much easier with an autogenerated surrogate key. 使用自动生成的代理密钥,一切将变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM