获取jpa中的列名称

Ger*_*man 7 jpa

我有一个查询工厂,它将列名作为属性,以便搜索该列.现在我将列的名称作为字符串传递,因此它是硬编码的.如果列的名称在实体的注释中发生更改,则"隐藏的依赖项"会中断.

在jpa中是否有一种方法可以检索列的真实名称并在编译时将其提供,因此我可以在查询中使用它?

top*_*hef 8

当然,总会有注释的反思.假设您有典型的JPA列定义:

    @Basic(optional = true)
    @Column(name = "MY_COLUMN_NAME_DESC", nullable = true, length = 255)
    public String getDesc() {
        return desc;
    }
Run Code Online (Sandbox Code Playgroud)

然后检查getter方法产生列名值(从这里采用的例子):

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

该示例假定JPA实体中的方法属性访问,但没有任何东西阻止您通过将反射应用于字段来将其采用到字段级别.