简体   繁体   English

如何获取任何JPA实体的主键?

[英]How to get the primary key of any JPA entity?

For every @Entity I need to perform the following: 对于每个@Entity,我需要执行以下操作:

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. 有了实体,我正试图到达@Entity,虽然我意识到这不是继承关系。 What class can I use to refer to every JPA entity? 我可以用什么类来引用每个JPA实体? I could just create an interface/abstract class MyEntities and have all of them inherit, but is that the way? 我可以创建一个接口/抽象类MyEntities并让所有这些继承,但是这样吗? 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(). 此外,当我尝试使用.getId()时,我希望能够提取每个实体的主键。

This functionality was added in JPA 2.0. 此功能已在JPA 2.0中添加。 Simply call: 只需致电:

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

Read an article about Generic Dao approach . 阅读有关Generic Dao方法的文章。

I don't clearly understand your problem, but if you want to get entity id - just get it. 我不清楚你的问题,但如果你想获得实体ID - 只需得到它。 Its available after persist method is complete ie 在持久化方法完成后可用

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. 我通常使用字段id及其访问器创建一个AbstractEntity类,并继承此类中的所有其他实体。

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 ie all other entities will become serializable. 这种方法的唯一问题是,如果您需要使任何实体Serializable,您必须使AbstractEntity序列化,即所有其他实体将变为可序列化。 Otherwise field id will not be serialized in the entity which should be serializable. 否则,字段id将不会在应该可序列化的实体中序列化。

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. 使用纯JPA我没有看到获取标识符的方法。

Have a look at merge() . 看看merge() I've not used it much myself but I think 我自己并没有太多地使用它,但我认为

Hibernate has ways of doing this Hibernate有办法做到这一点

Serializable id = session.getIdentifier(entity);

But this is not JPA standard. 但这不是JPA标准。

Another way of fetching entity ID is: 获取实体ID的另一种方法是:

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

This approach uses extractPrimaryKeyFromObject() method from ObjectBuilder class. 此方法使用ObjectBuilder类中的extractPrimaryKeyFromObject()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM