获取JPA中的列名 [英] Get column name in jpa
问题描述
我有一个查询工厂,该工厂将列名作为属性来搜索该列.现在,我将列名作为字符串传递,因此它是硬编码的.如果该列的名称在实体的注释中发生更改,则该隐藏的依赖项"将中断.
I have a query factory that takes a column name as an attribute in order to search for that column. Right now I'm passing the name of the column as a string, so it's kind of hardcoded. If the name of the column changes in the entity's annotation, that "hidden dependency" breaks up.
jpa中是否有一种方法可以检索列的真实名称并在编译时可用,所以我可以在查询中使用它?
Is there a way in jpa to retrieve the real name of the column and have it available at compile time, so I can use it in queries?
推荐答案
当然,注解总是存在反思.假设您具有典型的JPA列定义:
Of course, there is always reflection on annotations. Suppose you have typical JPA column definition:
@Basic(optional = true)
@Column(name = "MY_COLUMN_NAME_DESC", nullable = true, length = 255)
public String getDesc() {
return desc;
}
然后检查getter方法将产生列名值(示例取自此处):
Then having getter method inspected yields column name value (example adopted from 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实体,但是没有什么可以阻止您通过对字段应用反射将其应用于字段级别.
The example assumes method property access in JPA entity but nothing prevents you to adopt it to field level by applying reflection to a field.
这篇关于获取JPA中的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!