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
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in 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.
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 .
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());
}
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With