Hibernate – How to select an object’s class in HIbernate HQL

hibernatehql

how can I select an object's class in HQL? When I do the following:

select e.class, e.name from Entity e

Hibernate returns an Integer (e.g. [12, "name"]) instead of a class object. How can I return a Java class, or at least the class or entity name? Or, if this is not possible, how can I convert the 12 to a Java class?

For performance reasons, I can't query the full objects, i.e. I can't do

select e from Entity

Regards,
Jochen

Best Answer

if you are hibernate4, you can use HQL function 'type()' to get entity type

select type(e), e.name from Entity e

If you are hibernate3, the session.iterate() return entity as HibernateProxy with id only, and you can get entity name & id from it without initializing.

Iterator iterator = session.createQuery("from Entity e").iterate();
while(iterator.hasNext()) {
    HibernateProxy object = (HibernateProxy)iterator.next();
    System.out.println(object.getHibernateLazyInitializer().getIdentifier());
    System.out.println(object.getHibernateLazyInitializer().getEntityName());
}