Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an object's class in HIbernate HQL?

Tags:

hibernate

hql

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

like image 720
Jochen Avatar asked Mar 09 '12 08:03

Jochen


People also ask

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.

What is the difference between JPQL and HQL?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

How can I get single record in hibernate?

Use the uniqueResult() API method of Criteria to get the single instance that matches the query. Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction .


3 Answers

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());
}
like image 192
Rehtron Avatar answered Dec 29 '22 13:12

Rehtron


you can just use the addEntity() method to tell Hibernate to use your class to map the answer

 Query query = session.createSQLQuery(
    "select e.class,e.name from Entity e where <your conditions>")
    .addEntity(Entity.class)
    List<Entity> result = query.list();
like image 29
arkrad87 Avatar answered Dec 29 '22 11:12

arkrad87


Scalar HQL which explicitly specifies the column name in the select clause will return a list of object[] .Each index in the returned array match the corresponding column in the select clause.

To return a list of object , use select e from Entity e or simply from Entity .

List<Entity> result =   (List<Entity>) session.createQuery("from Entity").list();

To restrict the record returned by the HQL , apply some conditions in the where clause of the HQL, for example: from Entity e where e.name = xxxxx

like image 31
Ken Chan Avatar answered Dec 29 '22 11:12

Ken Chan