开发者

Extract the primary key from a entity object in JPA 2.0?

开发者 https://www.devze.com 2023-01-19 15:40 出处:网络
Let\'s say we have an entity object. Is there a way to extract a primary key from it? I want to do something like this:

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

I want to do something like this:

public static Object extractPrimaryKey(EntityManager em, Object obj) {
    return em.giveMeThePrimary开发者_JS百科KeyOfThisEntityObject(obj);
}

Reason for that is to get an attached copy of detached entity:

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)


Perhaps this will work:

em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(obj);


Reason for that is to get an attached copy of detached entity:

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

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

What's the problem with that?

0

精彩评论

暂无评论...
验证码 换一张
取 消