1

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.

Nitin Chhajer
  • 2,299
  • 1
  • 24
  • 35

1 Answers1

2

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.

Johanna
  • 5,223
  • 1
  • 21
  • 38
  • As this is duplicate it's not necessary to post responses. Between there already was an answer which could be considered as correct. – Artem Oboturov Apr 27 '12 at 14:43
  • @Artem Oboturov: It is not exactly a duplicate. In the question which you cited an aggregate function is selected, so only the possibility with new() works, but here only normal properties are selected, so there are two more possibilities, 2) and 3) in my answer, which only work here. – Johanna Apr 27 '12 at 14:53
  • I used the 3 option provided and it is working fine. Why is the `AliasToBeanResultTransformer` needed if it could work simply in this way? – Nitin Chhajer Apr 27 '12 at 15:29