tags:

views:

68

answers:

3

Hi,

I need to know which physical column is associated to a persistent's attribute.

e.g.

Class LDocLine has this attribute

  private Integer lineNumber;

which is mapped in hibernate like this :

  <property name="lineNumber" column="LINENUMBER" type="integer"/>

The method I need is something like :

getColumn("LDocLine","lineNumber) => "LINENUMBER"

I assume its existence internally, but not sure if it's in the public api.

Thanks in advance

A: 

This is something that Hibernate is not generally used for as you do not need to refer to column names in order to retreive objects through HQL or Criteria.

Why do you need this functionality?

Rachel
+4  A: 

Do you have access to Configuration object you've used to build your session factory? If so, you can use the following:

Value v = configuration.getClassMapping(entityName).getProperty(propertyName).getValue();
for (Iterator it = v.getColumnIterator(); it.hasNext(); ) {
  Column column = (Column) it.next();
  column.getName(); // or .getQuotedName() or bunch of other useful stuff
}

Column documentation.

If you don't have access to configuration, you can obtain column data from SessionFactory instance, however in this case you're technically no longer using public API as you'll have to class cast to internal implementations:

AbstractEntityPersister persister = (AbstractEntityPersister) sessionFactory.getClassMetadata(entityName);
String[] columnNames = persister.getPropertyColumnNames(propertyName);

In both cases entityName is the name of your entity (its class name unless explicitly overridden)

ChssPly76
I do not have access to the configuration object because a custom framework hides it, but it seems the way to go, I'll try to convince the team to make it available. Thanx!
Lluis Martinez
I used the second technique and worked perfectly, thanks a lot! Too bad ClassMetadata is so poor.
Lluis Martinez
+1  A: 

As you mentioned in your reply, you are not having access to 'Configuration' object.In case you are having access to hibernate 'Session' object, then following code may be helpful to you.

 Collection clsMetaData = session.getSessionFactory()
                .getAllClassMetadata().values();
        for (Iterator i = clsMetaData.iterator(); i.hasNext();) {
            ClassMetadata cmd = (ClassMetadata) i.next();
            System.out.println("cmd" + cmd.getEntityName());
            for (String s : cmd.getPropertyNames()) {
                System.out.println("prop:" + s);
            }

        }

In this way you can get details about Class metadata information.

lucentmind
Same solution as the previous answer but without the casting. Unfortunately ClassMetadata does not have the information I need.
Lluis Martinez