Extract primary key from entity object in JPA 2.0?

Let's say we have an entity object. Is there a way to extract the primary key from it?

I want to do something like this:

public static Object extractPrimaryKey(EntityManager em, Object obj) {
    return em.giveMeThePrimaryKeyOfThisEntityObject(obj);
}

The reason for this is to get an attached copy of a single object:

public static Object attach(EntityManager em, Object obj) {
    return em.find(obj.getClass(), extractPrimaryKey(em, obj));
}

Is it possible? (I am using EclipseLink 2.1)

+3
source share
2 answers

Maybe this will work:

em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(obj);
+3
source

The reason for this is to get an attached copy of a single object:

Why don't you just use EntityManager#merge(T)??

MyEntity detached = ...
MyEntity attached = em.merge(detached);

What is the problem with this?

+2
source

Source: https://habr.com/ru/post/1768462/


All Articles