18

How can I access the Hibernate mapping of my model to find out the column name of a property?

The column name is not specified in the mapping so Hibernate generates it automatically - I would like to create a native SQL statement including this column name.

David M
  • 71,481
  • 13
  • 158
  • 186
Thomas Einwaller
  • 8,873
  • 4
  • 40
  • 55

4 Answers4

16

Thanks to Jherico I found out how to do that:

((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
        .getProperty("myProperty").getColumnIterator().next()).getName();
Thomas Einwaller
  • 8,873
  • 4
  • 40
  • 55
3
((AbstractEntityPersister) sessionFactory.getClassMetadata(o.getClass()))
    .getPropertyColumnNames(property)[0];
B T
  • 57,525
  • 34
  • 189
  • 207
1

You have to have access to the Hibernate Configuration object.

Jherico
  • 28,584
  • 8
  • 61
  • 87
1

This will retrieve one-level composites and normal property mappings:

String columnName(String name) {
    PersistentClass mapping = configuration.getClassMapping(ExtendedPerson.class.getName());
    Property property = mapping.getProperty(name);
    if(property.isComposite()){
        Component comp = (Component) property.getValue();
        property = comp.getProperty(StringHelper.unroot(name));
        assert ! property.isComposite(); //go only one level down 
    }
    Iterator<?> columnIterator = property.getColumnIterator();
    Column col = (Column) columnIterator.next();
    assert ! columnIterator.hasNext();
    return col.getName();
}
Thomas Jung
  • 32,428
  • 9
  • 84
  • 114