简体   繁体   中英

JPA @IdClass - update

If you have a IdClass like

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.

Thx all

As for every other entity: you give an instance of the 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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