简体   繁体   English

JPA使用IdClass问题删除查询

[英]JPA removing query with IdClass issue

When I use a Idclass in JPA for a entity with a composite key and I write a remove method like : 当我在JPA中使用Idclass用于具有复合键的实体时,我编写了一个remove方法,如:

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

I get the error : 我收到错误:

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

When I change the code to : 当我将代码更改为:

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

I don't get any errors but I wonder if this is the right way to do this? 我没有得到任何错误,但我想知道这是否是正确的方法吗?

Yes, it's the right way to do it. 是的,这是正确的方法。 The EntityManager.find() method expects an instance of the ID class of the entity. EntityManager.find()方法需要实体的ID类的实例。 Not some random attribute of the entity. 不是实体的一些随机属性。

Note that the error isn't caused by the remove() method, but by the find() method. 请注意,错误不是由remove()方法引起的,而是由find()方法引起的。

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

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