【问题标题】:How can I get the fieldnames of the PK (@Id) of a JPA @Entity如何获取 JPA @Entity 的 PK (@Id) 的字段名
【发布时间】:2014-03-04 18:13:41
【问题描述】:

我正在使用 JPA2 (Hibernate 4) 并且有一堆 @Entity 类,我的 PK 是使用 @Id 定义的。如何以编程方式检索每个实体类的 PK 的字段名?

对此的商业案例是我想使用 Spring 的 BeanUtils.copyProperties 方法复制实体对象,但要确保在复制时忽略实体的 id 字段。

有没有办法找到这些信息? JPA 是否提供此信息?我意识到我可以使用反射来完成每一堂课,但希望有一个更简单的解决方案。我查看了扫描类的PropertyDescriptors,但似乎在 PropertyDescriptor 上找不到任何可以为我提供属性注释的方法。

【问题讨论】:

    标签: spring hibernate jpa-2.0 primary-key


    【解决方案1】:

    试试这个:

    @PersistenceUnit
    private EntityManagerFactory emf;
    
    Metamodel metamodel = emf.getMetamodel();
    metamodel.entity(MyEntity.class).getId();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2014-03-12
      • 2011-11-30
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多