如何获取任何JPA实体的主键? [英] How to get the primary key of any JPA entity?

查看:215
本文介绍了如何获取任何JPA实体的主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于每个@Entity,我需要执行以下操作:

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;
}

如果实体不存在,这是持久的,并知道它是否存在是否存在。
使用Entity我正试图联系@Entity,虽然我意识到这不是继承关系。
我可以使用哪个类来引用每个JPA实体?我可以创建一个接口/抽象类MyEntities并让所有这些继承,但是这样吗?
我希望减少代码。此外,我希望能够提取每个实体的主键,因为我尝试.getId()。

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

推荐答案

此功能已在JPA 2.0中添加。只需调用:

This functionality was added in JPA 2.0. Simply call:

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

这篇关于如何获取任何JPA实体的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆