How to get the primary key of any JPA entity?

核能气质少年 提交于 2019-11-27 14:49:02

问题


For every @Entity I need to perform the following:

public <Entity> boolean insert(final Entity entity){
    if (em.find(entity.getClass(), entity.getId()) == null) {
        et.begin();
        em.persist(entity);
        et.commit();
        return true;
    }
    return false;
}

That is persist the entity if it didn't exist, and know if it did or not exist. With Entity I'm trying to reach @Entity, although I realize it's not an inheritance relationship. What class can I use to refer to every JPA entity? I could just create an interface/abstract class MyEntities and have all of them inherit, but is that the way? I'm hoping for less code. Also, I'd expect to be able to extract the primary key of every entity, as I attempt in .getId().


回答1:


This functionality was added in JPA 2.0. Simply call:

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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3328813/how-to-get-the-primary-key-of-any-jpa-entity

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