How to select an object class in HIbernate HQL?

How can I select an object class in HQL? When I do the following:

select e.class, e.name from Entity e 

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

For performance reasons, I cannot request complete objects, i.e. I can not perform

 select e from Entity 

Regards, Jochen

+6
source share
4 answers

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

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

If you are hibernate3, session.iterate () returns an object as HibernateProxy with only an identifier, and you can get the name and identifier of an entity from it without initialization.

 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()); } 
+8
source

you can simply use the addEntity () method to tell Hibernate to use your class to match the response

  Query query = session.createSQLQuery( "select e.class,e.name from Entity e where <your conditions>") .addEntity(Entity.class) List<Entity> result = query.list(); 
+4
source

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

To return a list of objects, use select e from Entity e or just from Entity .

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

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

+1
source

If you want to limit the number of columns in the select list , you can use the new operator inside hql .

I.e

 select new Entity(e.class, e.name) from Entity e 

Also, add the appropriate constructor to the Entity class, which can use this query.

This will give you a List<Entity> , initialized with just two values.

This is useful when you need a snapshot of a Large object in performative mode. Read here for API docs or here .

0
source

Source: https://habr.com/ru/post/910325/


All Articles