【发布时间】:2011-11-30 15:28:28
【问题描述】:
标题是不言自明的。
我很高兴听到解决方案,谢谢。
【问题讨论】:
-
需要名字,还是值也可以?
-
其实我需要的是名字本身,而不是值。
标签: hibernate jpa annotations ejb-3.0
标题是不言自明的。
我很高兴听到解决方案,谢谢。
【问题讨论】:
标签: hibernate jpa annotations ejb-3.0
我不是 Java 程序员,也不是 Hibernate 注释的用户......但我可能仍然可以提供帮助。
此信息在元数据中可用。您可以从会话工厂获取它们。我看起来像这样:
ClassMetadata classMetadata = getSessionFactory().getClassMetadata(myClass);
string identifierPropertyName = classMetadata.getIdentifierPropertyName();
【讨论】:
我扩展了这个答案:How to get annotations of a member variable?
试试这个:
String findIdField(Class cls) {
for(Field field : cls.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
Annotation[] annotations = field.getDeclaredAnnotations();
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].annotationType().equals(Id.class)) {
return name;
}
}
}
return null;
}
【讨论】:
JPA2 有一个元模型。只需使用它,然后您就可以保持符合标准。任何 JPA 实现的文档都应该为您提供有关如何访问元模型的足够信息
【讨论】:
ClassMetadata.getIdentifierPropertyName() 如果实体具有包含嵌入键多对一的复合 ID,则返回 null。
所以这个方法不涵盖这些情况。
【讨论】:
有一个比目前列出的更短的方法:
Reflections r = new Reflections(this.getClass().getPackage().getName());
Set<Field> fields = r.getFieldsAnnotatedWith(Id.class);
【讨论】:
这适用于 EclipseLink 2.6.0,但我预计 Hibernate 空间不会有任何差异:
String idPropertyName;
for (SingularAttribute sa : entityManager.getMetamodel().entity(entityClassJpa).getSingularAttributes())
if (sa.isId()) {
Preconditions.checkState(idPropertyName == null, "Single @Id expected");
idPropertyName = sa.getName();
}
【讨论】:
聚会有点晚了,但是如果您碰巧知道您的实体只有一个 @Id 注释并且知道 id 的类型(在这种情况下为整数),您可以这样做:
Metamodel metamodel = session.getEntityManagerFactory().getMetamodel();
String idFieldName = metamodel.entity(myClass)
.getId(Integer.class)
.getName();
【讨论】: