查找使用类ID的实体

时间:2017-12-07 08:22:17

标签: jpa eclipselink jpql entitymanager

要使用主键从实体中查找对象,我们使用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对象?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

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

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

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