views:

35

answers:

2

I have a piece of maintenance code that should grant select privileges to a certain user at certain points of 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 tab in Oracle or show tables in MySQL to get the complete list and then move on like that.

But since I already have the javax.persistence.EntityManager Object at hand, I wondered if there is another way to get at all the mapped Entities, the Manager knows about (I am using Hibernate under the hood).

A: 

Check what's available in this Map:

((Session) entityManager.getDelegate()).getSessionFactory().getAllClassMetadata() ;
Bozho
The class metadata is really limited to the properties of the entity itself and doesn't contain any mapping-related data. This would be fine if the DB tables are named the same as the Entities.
BryanD
well, it looks like getAllClassMetadata was the solution sought. Your answer was more detailed, of course.. I should perhaps not give hints, but complete solutions. Still, I feel there's something wrong with that :)
Bozho
+1  A: 

There are two ways that I can see getting all of the mapped entities and their corresponding SQL tables (there may be others).

The most straightfoward is if you can use your Hibernate Configuration object:

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

Alternatively, you can do a little more casting and get this same information out of the SessionFactory too:

    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);
    }
BryanD
I cannot get to the Hibernate Configuration but the second solution works.
raoulsson