Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Hibernate, how can I query a table and return a hashmap with key value pair id>name?

Tags:

sql

hibernate

hql

I've got this table :

table name : Account
Fields : id (varchar), name(varchar), other fields...

I want to query this table with hibernate mechanism (to use the second cache level). The result of the hibernate query must be a hash map where the key is the field id and where the value is the field name.

How can I write it with HQL ?

If I use map, I can only use alias and if I use a constructor with an object, I must transform result to hashmap which is time consuming.

Example : 
Id | name | other fields
1 Jerome ...
2 Steve ...
3 Nick ...

the result of the query must be a hashmap :

1>Jerome
2>Steve
3>Nick

thanks

like image 497
Jerome Cance Avatar asked Jan 19 '11 14:01

Jerome Cance


1 Answers

This question is old but this might still help other people. You can now use HQL to return maps with hibernate. Use something like this:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n ) from Cat cat

From hibernate docs: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select

like image 188
tbraun Avatar answered Oct 07 '22 16:10

tbraun