Retrieving All Mapped Objects from EnitityManager

I have a service code that should provide certain privileges to a specific user at certain points in time:

grant select on A_DB.A_TABLE to READ_ONLY_USER;

I want to do this for all tables. I could use select * from tabin Oracle or show tablesin MySQL to get a complete list, and then move like that.

But since I already have the object javax.persistence.EntityManagerat hand, I wondered if there was another way to get all the mapped objects that the manager knows about (I use Hibernate under the hood).

+5
source share
4 answers

SQL ( ).

- Hibernate:

    for(Iterator it = config.getClassMappings(); it.hasNext();){
        PersistentClass pc = (PersistentClass) it.next();
        System.out.println(pc.getEntityName() + "\t" + pc.getTable().getName());
    }

SessionFactory :

    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();
        System.out.println(entityName + "\t" + tableName);
    }
+9

2016 (Hibernate 5.2), getAllClassMetadata Configuration .

, :

Set<EntityType<?>> entities = sessionFactory.getMetamodel().getEntities();

:

List<?> classes = entities.stream()
                          .map(EntityType::getJavaType)
                          .filter(Objects::nonNull)
                          .collect(Collectors.toList());
+5

Check what is available in this Map:

((Session) entityManager.getDelegate()).getSessionFactory().getAllClassMetadata() ;
0
source

If you have javax.persistence.EntityManager in hand., The following method can help you get a list of 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
source

All Articles