7

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?

German
  • 3,560
  • 7
  • 32
  • 34

2 Answers2

8

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.

Community
  • 1
  • 1
topchef
  • 19,091
  • 9
  • 63
  • 102
1

This is a bit late, I know. Topchef's answer is correct, but there are a couple of other factors that need to be considered if you want this to work for arbitrary entity classes. I'm adding them in case someone comes across this answer in a web search:

  • The AttributeOverride class annotation can override the column specified with the Column annotation.
  • If the inheritance strategy is JOINED, the column may reside in a different table even if a table is not specified with the Column annotation.
Alvin Thompson
  • 5,388
  • 3
  • 26
  • 39
  • Is there JPA API to get column annotation for a property? merging XML, AttributeOverride, @Column. Thanks. – eastwater May 19 '15 at 14:26
  • @Dave: none that I'm aware of I'm afraid, but I haven't checked in the last year or three. I needed to do this in the past and also wound up merging the sources you mentioned. Very nasty, complex code to recreate something JPA must do anyway. Perhaps going through Hibernate or EclipseLink directly provides a way... – Alvin Thompson May 19 '15 at 18:32
  • It seems they do not provide such public API. Internally they must have something to merge configurations from difference sources. – eastwater May 22 '15 at 15:15