tags:

views:

1929

answers:

6

How do I get the table name for a model in Hibernate?

Apparently there used to be a getTableName() method in ClassMetadata, but it's been removed.

There's a getClassMapping(String entityName) method in Configuration, but I don't know how I can (or if I should) use Configuration from within my DAO implementation.

My DAO implementation is a subclass of HibernateGeneralGenericDao.

UPDATE: It turns out I can do what I'm trying to do without the table name. However, I will keep the question open (and try the answers as they come) for the sake of reference.

A: 

maybe use SessionFactory.getClassMetadata ?

Michael Lange
Yes, I tried that, but ClassMetadata doesn't seem to contain any information regarding the table
Can Berk Güder
+4  A: 

If you're using the Table annotation you could do something like this:

Table table = Entity.class.getAnnotation(Table.class);
String tableName = table.name();
Alex Rockwell
I'm not (and honestly, I just learned about annotations), but this is a nice idea. Thanks.
Can Berk Güder
A: 

Using the Configuration, you can call the GetClassMapping() method for a specific type, which would give you some mapping information for that type.

(At least, this is the case in NHibernate, but I suppose that this will be similar in Hibernate).

Frederik Gheysels
Yes, but how do I use Configuration? Can I just create a new instance?
Can Berk Güder
Some options are to create a new instance like during initialization; keep it around as a static or singleton; or use reflection to grab it from the SessionFactory. Once you have the configuration: configuration.getClassMapping("foo").getTable().getName();
Brian Deterling
+2  A: 

It's a bit weird but it works:

ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(pClassName);
if (hibernateMetadata == null){
    return;
}
if (hibernateMetadata instanceof AbstractEntityPersister)){
     AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;
     String tableName = persister.getTableName();
     String[] columnNames = persister.getKeyColumnNames();
}
FoxyBOA
A: 
Configuration cfg = new Configuration().configure();    
cfg.addResource("com/struts/Entities/User.hbm.xml");
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
Mappings m=cfg.createMappings();
System.out.println(">> class: "+m.getClass(className));
System.out.println("User table name:: "+m.getClass("User").getTable().getName());