1
當我在JPA使用Idclass與複合鍵的實體,我寫這樣一個remove方法:JPA與IdClass問題刪除查詢
private static void removeEmployee(Employee employee) {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPA_excer_3b");
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
Employee anemployee = em.find(Employee.class, employee.getId());
em.remove(anemployee);
em.getTransaction().commit();
} catch (Exception e) {
logging.error("This error is added a removing a employee :"
+ " :" + e);
} finally {
// Close all the connections:
em.close();
emf.close();
}
}
我得到的錯誤:
ERROR Logger:22 - This error is added a removing a employee :java.lang.IllegalArgumentException: Provided id of the wrong type for class be.leerstad.JPA.entities.Employee. Expected: class be.leerstad.JPA.entities.EmployeePK, got class java.lang.Integer
當我將代碼更改爲:
private static void removeEmployee(Employee employee) {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPA_excer_3b");
EntityManager em = emf.createEntityManager();
try {
**EmployeePK pk = new EmployeePK(employee.getId(),employee.getEmail());**
em.getTransaction().begin();
Employee anemployee = em.find(Employee.class, **pk**);
em.remove(anemployee);
em.getTransaction().commit();
} catch (Exception e) {
logging.error("This error is added a removing a employee :"
+ " :" + e);
} finally {
// Close all the connections:
em.close();
emf.close();
}
}
我沒有得到任何錯誤,但我不知道這是否是正確的方法來做到這一點?
請分享您的實體和關鍵類 –