Get all table names set up in SessionFactory

前端 未结 4 1273
你的背包
你的背包 2020-12-16 05:52

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 AnnotationConfi

相关标签:
4条回答
  • 2020-12-16 06:10

    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(); 
    
    0 讨论(0)
  • 2020-12-16 06:20
    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

    0 讨论(0)
  • 2020-12-16 06:25

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 06:31

    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 讨论(0)
提交回复
热议问题