Get column name in jpa

I have a factory query that takes a column name as an attribute to search for that column. Right now I am passing the column name as a string, so it looks like hardcoded. If the column name changes in the annotation of the object, this “hidden dependency” breaks up.

Is there a way in jpa to get the true name of the column and have it available at compile time, so I can use it in queries?

+6
jpa
source share
2 answers

Of course, there is always a reflection of annotations. Suppose you have a typical JPA column definition:

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

Then, checking the getter method returns the value of the column name (an example is 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 a method for accessing properties in a JPA entity, but nothing prevents you from moving it to the field level by applying reflection to the field.

+6
source share

It's a little late, I know. Topchef's answer is correct, but there are several other factors that need to be considered if you want this to work for arbitrary entity classes. I add them if someone encounters this answer in a web search:

  • Antibodies of the AttributeOverride class can override the column specified in the column annotation.
  • If the inheritance strategy is JOINED, the column may reside in another table, even if the table is not specified with column annotation.
+1
source share

All Articles