查找使用 class ID 的实体

Find an entity which use a class Id

要从具有主键的实体中查找对象,我们使用 em.find(Person.class, <Id>)

我正在使用 JPA EclipseLink,我有一个具有复合主键 (@classId) 的 Person 实体,

Person 实体:

@Entity
    @IdClass(PersonId.class)
    public class Person {

@Id
private int id;

@Id
private String name;

public String getName() {
    return name;
}

// getters & setters
}

和 PersonID:

public class PersonId implements Serializable {

private static final long idVersionUID = 343L;

private int id;
private String name;

// must have a default construcot
public PersonId() {

}

public PersonId(int id, String name) {
    this.id = id;
    this.name = name;
}

//getters & setters
//hachCode & equals
}

如何使用em.find获取Person对象?

我找到了解决方案:

    PersonId carId = new PersonId(33, "Jhon");

    Person persistedPerson = em.find(Person.class, carId);

    System.out.println(persistedPerson.getID() + " - " + persistedPerson.getName());