gpt4 book ai didi

java - JPA 删除带有 IdClass 问题的查询

转载 作者:行者123 更新时间:2023-11-29 05:50:56 25 4
gpt4 key购买 nike

当我在 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();
}
}

我没有收到任何错误,但我想知道这样做是否正确?

最佳答案

是的,这是正确的做法。 EntityManager.find() 方法需要一个实体 ID 类的实例。不是实体的一些随机属性。

请注意,错误不是由 remove() 方法引起的,而是由 find() 方法引起的。

关于java - JPA 删除带有 IdClass 问题的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13902165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com