Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column name in jpa

Tags:

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.

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?

like image 282
German Avatar asked May 27 '10 13:05

German


1 Answers

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;
    }

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());
    }
}

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.

like image 182
topchef Avatar answered Nov 08 '22 22:11

topchef