Nitin Chhajer
Nitin Chhajer

Reputation: 2339

How to get HQL output in a common class

I have a common HQL for multiple classes

Query query = session.createQuery("select id, name from " + hibernateClass.getClass().getName());

query.list(); returns a List<Object[]>. Now the output of the query has the same structure i.e. a Long id and a String name. So is it possible to put this content in a class, so that when I call query.list() everything gets copied into a list and I don't have to create a new List object and populate it.

Upvotes: 1

Views: 445

Answers (1)

Johanna
Johanna

Reputation: 5303

There are some possibilities which lead to a similar result (lets assume you want to have a List<NewClass> as result with NewClass just having the properties id and name):

1) You do createQuery("select new NewClass(id, name) from " + hibernateClass.getClass())

2) You create a new mapping file for NewClass for the same database table but only with the properties id and name and then your query is createQuery("from " + NewClass.class)

3) You just do createQuery("from " + hibernateClass.getClass()) and you don't case about the superfluous values which where loaded. The extra amount of time for loading all columns compared to loading only the necessary columns is insignificant. If you prefer, you can nevertheless create a class or interface NewClass and for HibernateClass extends/implements NewClass.

Me personally I prefer 3), but that's up to your taste.

Upvotes: 2

Related Questions