【发布时间】:2010-05-27 13:21:34
【问题描述】:
我有一个查询工厂,它以列名作为属性来搜索该列。现在我将列的名称作为字符串传递,所以它是硬编码的。如果实体注释中的列名称发生变化,那么“隐藏的依赖关系”就会中断。
在 jpa 中有没有办法检索列的真实名称并在编译时提供它,以便我可以在查询中使用它?
【问题讨论】:
标签: jpa
我有一个查询工厂,它以列名作为属性来搜索该列。现在我将列的名称作为字符串传递,所以它是硬编码的。如果实体注释中的列名称发生变化,那么“隐藏的依赖关系”就会中断。
在 jpa 中有没有办法检索列的真实名称并在编译时提供它,以便我可以在查询中使用它?
【问题讨论】:
标签: jpa
当然,注释总是有反思的。假设您有典型的 JPA 列定义:
@Basic(optional = true)
@Column(name = "MY_COLUMN_NAME_DESC", nullable = true, length = 255)
public String getDesc() {
return desc;
}
然后检查 getter 方法会产生列名值(示例取自 here):
Method method = ... //obtain entity object
Annotation[] annotations = method.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof Column){
Column myAnnotation = (Column) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
该示例假定 JPA 实体中的方法 property access,但没有什么可以阻止您通过将反射应用于字段来将其应用于字段级别。
【讨论】:
这有点晚了,我知道。 Topchef 的回答是正确的,但是如果您希望它适用于任意实体类,还需要考虑其他几个因素。我添加它们以防有人在网络搜索中遇到此答案:
【讨论】: