Thomas Einwaller
Thomas Einwaller

Reputation: 9063

Get column name of property mapped with Hibernate

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.

Upvotes: 18

Views: 30254

Answers (4)

B T
B T

Reputation: 60875

((AbstractEntityPersister) sessionFactory.getClassMetadata(o.getClass()))
    .getPropertyColumnNames(property)[0];

Upvotes: 3

Thomas Jung
Thomas Jung

Reputation: 33092

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

Upvotes: 1

Thomas Einwaller
Thomas Einwaller

Reputation: 9063

Thanks to Jherico I found out how to do that:

((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
        .getProperty("myProperty").getColumnIterator().next()).getName();

Upvotes: 16

Jherico
Jherico

Reputation: 29240

You have to have access to the Hibernate Configuration object.

Upvotes: 1

Related Questions