The following code was written for EclipseLink but should be compatible with TopLink Essentials with some minor changes.
Doug
import java.util.Vector;
import javax.persistence.EntityManager;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.internal.jpa.CMP3Policy;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.jpa.JpaHelper;
/**
*
* @author djclarke
*
*/
public class PKHelper {
/**
*
* @param entity
* @return
* @throws IllegalArgumentException
* if the class passed in is not an entity or the provided
* EntityManager is not an EclipseLink implementation.
*/
public static Object extractPrimaryKey(EntityManager em, Object entity) {
if (entity == null) {
return null;
}
JpaEntityManager emImpl = JpaHelper.getEntityManager(em);
if (em == null) {
throw new IllegalArgumentException(
"EntityManager is either not EclipseLink's or its a container wrapper returniong null from getDelegate()");
}
ClassDescriptor descriptor = emImpl.getSession().getClassDescriptor(
entity.getClass());
if (descriptor == null || !descriptor.hasCMPPolicy()) {
throw new IllegalArgumentException("Entity: " + entity
+ " does not have a valid descriptor to extract the PK");
}
Vector pks = descriptor.getObjectBuilder().extractPrimaryKeyFromObject(entity, (AbstractSession) emImpl.getSession());
if (pks.size() == 1) {
return pks.get(0);
}
CMP3Policy policy = (CMP3Policy) descriptor.getCMPPolicy();
return policy.createPrimaryKeyInstance(pks);
}
}
-----Original Message-----
From: Aleksei Valikov [mailto:aleksei.valikov_at_gmail.com]
Sent: Saturday, July 26, 2008 7:13 AM
To: persistence_at_glassfish.dev.java.net
Subject: Re: Getting the entity id with JPA
Hi.
> There may be more than 1 @Id annotation if the entity defines @IdClass on
> it.
Yes, I know, the code I've posted does not pretend to be complete.
The question is if there is a standard way to get the id of the entity
(like, an oppositoe of getting the entity by its id). The trick with
annotations works, but what if entities are mapped using the XML
mappings?
Bye.
/lexi