Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA get id of entity object

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).

like image 555
ibhana Avatar asked Nov 05 '10 14:11

ibhana


2 Answers

In JPA 2.0 you can write

em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(instance);
like image 102
axtavt Avatar answered Sep 20 '22 22:09

axtavt


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.

like image 21
Pascal Thivent Avatar answered Sep 17 '22 22:09

Pascal Thivent