How to get the primary key of any JPA entity?

删除回忆录丶 提交于 2019-11-29 01:39:20
Gordon Yorke

This functionality was added in JPA 2.0. Simply call:

Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);

Read an article about Generic Dao approach.

I don't clearly understand your problem, but if you want to get entity id - just get it. Its available after persist method is complete i.e.

em.persist(entity);
et.commit();
int id = entity.getId()

I usually make a class AbstractEntity with field id and its accessors and inherit all my other entities from this class.

The only problem with this approach is that if you'll need to make any of your entities Serializable, you'll have to make AbstractEntity serializable i.e. all other entities will become serializable. Otherwise field id will not be serialized in the entity which should be serializable.

The common interface approach is what I use and it works fine. Using pure JPA I don't see a way of getting the identifier.

Have a look at merge(). I've not used it much myself but I think

Hibernate has ways of doing this

Serializable id = session.getIdentifier(entity);

But this is not JPA standard.

Another way of fetching entity ID is:

Session session = entityManager.unwrap(Session.class);
Object entityId = session.getId(entity);

This approach uses extractPrimaryKeyFromObject() method from ObjectBuilder class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!