JPA get id of entity object
Asked Answered
P

2

11

Does anyone know how I can do the equivalent of this in hibernate:

session.getIdentifier(instance);

with JPA?

EntityManager has a contains method but that's pretty much it!

I'm writing some code that acts as a transformer between entities and data stored in a session (so rather than a serialized object being stored just the class name and the id is stored).

Pyrolysis answered 5/11, 2010 at 14:42 Comment(0)
B
10

Does anyone know how I can do the equivalent of this in hibernate (...) with JPA?

JPA 1.0 doesn't have an equivalent so if you're stuck with JPA 1.0, you'll have to use Hibernate's API: obtain the Session from the EntityManager and use Session#getIdentitifier(Object).

For example, with JBoss (yes, getDelegate() is not portable):

org.hibernate.Session session = (Session)manager.getDelegate();
session.getIdentifier(myEntity);

If you are using JPA 2.0, then use PersistenceUnitUtil#getIdentity(Object) as suggested by axtavt. But that's not available in JPA 1.0.

Basidiomycete answered 6/11, 2010 at 21:47 Comment(1)
Thanks for the detailed answer. The non-portable solution should work fine hopefully as a temporary fix.Pyrolysis
M
21

In JPA 2.0 you can write

em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(instance);
Matz answered 5/11, 2010 at 14:50 Comment(2)
+1 (I was searching through the depths of MetaModel and EntityType, but it never occurred to me to look inside EntityManagerFactory).Tosch
Thanks, I'll have to think about upgrading to JPA 2.0.Pyrolysis
B
10

Does anyone know how I can do the equivalent of this in hibernate (...) with JPA?

JPA 1.0 doesn't have an equivalent so if you're stuck with JPA 1.0, you'll have to use Hibernate's API: obtain the Session from the EntityManager and use Session#getIdentitifier(Object).

For example, with JBoss (yes, getDelegate() is not portable):

org.hibernate.Session session = (Session)manager.getDelegate();
session.getIdentifier(myEntity);

If you are using JPA 2.0, then use PersistenceUnitUtil#getIdentity(Object) as suggested by axtavt. But that's not available in JPA 1.0.

Basidiomycete answered 6/11, 2010 at 21:47 Comment(1)
Thanks for the detailed answer. The non-portable solution should work fine hopefully as a temporary fix.Pyrolysis

© 2022 - 2024 — McMap. All rights reserved.