3

I have a table T with columns defined as usual.

@Entity
@Table(name="T")
public class T {
@Column(name="test_id")
private Long testId;

}

Given entity property "testId", I want to get corresponding DB column name (i.e. "test_id"). How could it be achieved?

Edit 1: I want to keep this column at separate location with actual DB column name (test_id) than testId. I fetched these values from DB using HQL which have key as entity name (i.e. testId) and I want actual column name in DB.

instanceOfObject
  • 2,936
  • 5
  • 49
  • 85

2 Answers2

5

If I understood your requirement correctly, you want to use HQL while having a consistent name for both DB column and the entity field, like this:

SELECT t.test_id FROM Test t 

instead of

SELECT t.testId FROM Test t 

There is only one way to do that - renaming the field to test_id. HQL works on entities, not on DB tables, so you must use proper field names in the query.

Since test_id contradicts the usual Java coding conventions, I would advise against it.

EDIT: Getting the annotation attribute value with reflection would work along this outline:

Field field = MyEntity.class.getDeclaredField("testId");
Column a = field.getAnnotation(Column.class);
String columnName = a.name();
Slapy
  • 317
  • 3
  • 9
kostja
  • 60,521
  • 48
  • 179
  • 224
  • I understand that HQL works on entities. What I want is to get DB column name from entity property (get test_id from testId). I have read that Hibernate Configurations could be used for this but not quite sure of the way. – instanceOfObject Feb 06 '14 at 13:37
  • 1
    So you want to extract the `name` attribute of the Column annotation, you could use reflection for that. Or am I misunderstanding you again? – kostja Feb 06 '14 at 13:42
  • Correct! Reflection is one way to do this :) – instanceOfObject Feb 06 '14 at 14:01
3

I would try to avoid this by any means, but if you're really sure you'll need it, use:

Configuration configuration = sessionFactory.getConfiguration();
PersistentClass persistentClass = configuration
                .getClassMapping(T.class.getName());
String columnName = ((Column) persistentClass.getProperty("testId")
                .getColumnIterator().next()).getName();

See also Get table column names in Hibernate

Community
  • 1
  • 1
GeertPt
  • 16,398
  • 2
  • 37
  • 61