Saturday, December 27, 2014

How to get all table names using Hibernate.

This post demonstrates the how to get the all table names using Hibernate.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();

// Way1 - get the all Class Mapping Information using Configuration
Iterator<PersistentClass> classMappings = configuration.getClassMappings();
while(classMappings.hasNext()) {
PersistentClass persistentClass = classMappings.next();
Table table = persistentClass.getTable();
String tableName = table.getName();
System.out.println(tableName);
}

// Way2 - get the all Class Metadata Information using SessionFactory
Map<String, ClassMetadata> classMetaDataMap = sessionFactory.getAllClassMetadata();
for(Map.Entry<String, ClassMetadata> metaDataMap : classMetaDataMap.entrySet()) {
ClassMetadata classMetadata = metaDataMap.getValue();
AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata;
String tableName = abstractEntityPersister.getTableName();
System.out.println(tableName);
}

// Way3 - using Session
SessionImpl sessionImpl = (SessionImpl) sessionFactory.openSession();
try {
Connection connection = sessionImpl.connection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
ResultSet resultSet = databaseMetaData.getTables(null, null, null, new String[] {"TABLE"});
while(resultSet.next()) {
String tableName = resultSet.getString(3);
System.out.println(tableName);
}
} catch (Exception e) {
e.printStackTrace();
}
References:
  • https://stackoverflow.com/questions/4813122/get-all-table-names-set-up-in-sessionfactory
  • http://www.herongyang.com/JDBC/sqljdbc-jar-Table-List.html
  • http://tutorials.jenkov.com/jdbc/databasemetadata.html

3 comments: