[ACCEPTED]-Get all table names set up in SessionFactory-hibernate

Accepted answer
Score: 13

Here is howto getting one tableName with 2 getClassMetadata

ClassMetadata cm = sessionFactory.GetClassMetadata(className);

AbstractEntityPersister aep = (AbstractEntityPersister) cm;
String tableName = aep.getTableName();

[EDIT] : you can find all by calling getAllClassMetadata() and find 1 all table names like that

Map m = sessionFactory.GetAllClassMetadata();
/* iterate map*/
AbstractEntityPersister aep = m.get(/*key (className)*/) 
String tableName = aep.getTableName(); 
Score: 2

If you are using JPA instead of direct dependency 2 on hibernate., following code should help 1 in getting all table names

private List<String> getAllTables() {
    List<String> tableNames = new ArrayList<>();
    Session session = entityManager.unwrap(Session.class);
    SessionFactory sessionFactory = session.getSessionFactory();
    Map<String, ClassMetadata>  map = (Map<String, ClassMetadata>) sessionFactory.getAllClassMetadata();
    for(String entityName : map.keySet()){
        SessionFactoryImpl sfImpl = (SessionFactoryImpl) sessionFactory;
        String tableName = ((AbstractEntityPersister)sfImpl.getEntityPersister(entityName)).getTableName();
    return tableNames;
Score: 2

is deprecated. Use

    Metamodel metamodel = entityManager.getMetamodel();
    Set<EntityType<?>> entities = metamodel.getEntities();

    entities.forEach(e -> {

Your can also get metamodel from 1 SessionFactory

Score: 1

You can try using native sql queries.

session.createSQLQuery("SELECT * FROM user_tables").list();

which 5 gives list of tables owned by loggedin user 4 or else you can use 'all_tables' or 'dba_tables' for 3 all the tables for oracle database.If mysql 2 db is used then replace the query with "SHOW 1 TABLES"

More Related questions