开发者

Get all table names set up in SessionFactory

Is there a way to retrieve the name of all tables that are managed by the SessionFactory? For instance, all the tables that were added via Annotat开发者_Python百科ionConfiguration.addAnnotatedClass(...))?


Here is howto getting one tableName with getClassMetadata

ClassMetadata cm = sessionFactory.GetClassMetadata(className);

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

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

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


If you are using JPA instead of direct dependency on hibernate., following code should help 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();
        tableNames.add(tableName);
    }
    return tableNames;
}


sessionFactory.GetClassMetadata(className);

is deprecated. Use

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

    entities.forEach(e -> {
        System.out.println(e.getName());
    });

Your can also get metamodel from SessionFactory


You can try using native sql queries.

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜