Search code examples
jpaeclipselinkjpqlentitymanager

Find an entity which use a class Id


To find an object from entity with primary key we use em.find(Person.class, <Id>).

I'm using JPA EclipseLink and I have a Person entity which has a composite primary key(@classId),

the Person entity:

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

@Id
private int id;

@Id
private String name;

public String getName() {
    return name;
}

// getters & setters
}

and the 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
}

How to use em.find to get a Person object?


Solution

  • I found the solution :

        PersonId personeId = new PersonId(33, "Jhon");
        
        Person persistedPerson = em.find(Person.class, personeId);
        
        System.out.println(persistedPerson.getID() + " - " + persistedPerson.getName());