Close

JPA - IllegalArgumentException: You have provided an instance of an incorrect PK ....

[Last Updated: Apr 21, 2017]

JPA 

This exception occurs when using EclipseLink as JPA provider.

Exception in thread "main" java.lang.IllegalArgumentException: You have provided an instance of an incorrect PK class for this find operation.  Class expected : class java.lang.Long, Class received : class java.lang.Integer.
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.findInternal(EntityManagerImpl.java:806)
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:730)
	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:599)
    .......

Following is the code snippet, where we got the exception:

@Entity
public class Employee {
@Id
private long myId;
......
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test1");
.....
EntityManager em = emf.createEntityManager();
MyEntity myEntity = em.find(MyEntity.class, 1);
.....

Looks like, the exception is in consistent with following lines from EntityManager docs but we were expecting auto conversion where possible.

IllegalArgumentException - if the first argument does not denote an entity type or the second argument is not a valid type for that entity's primary key or is null

The fix:

MyEntity myEntity = em.find(MyEntity.class, 1L);

See Also