Query Several Columns With Hibernate


Even though Hibernate is called an object-relational mapper it's easy to select only a few properties instead of the whole mapped object. The hibernate query language (HQL) is very expressive. If you select some properties instead of the whole object, the call of Query#list() returns a list of object arrays. Each field of the array contains one of the selected properties.

select c.name, c.order from
Customer c;

In my opinion iterating over lists of Object[] is verbose and error-prone because processing the result-list is directly dependant on the sequence of selected properties in the hql string. If you change the query string you have to change the sourcecode as well. Did I mention how expressive HQL is? :) Check out the following snippet:

select new map(c.name as name, c.order as order)
from Customer c;

Instead of returning arrays this query will return a list of maps each containing entries with aliases (the keys) to selected values. Actually it's possible to let Hibernate return partially loaded entities instead of maps containing the properties of interest. Check out the following example:

select new Customer(c.name, c.order)
from Customer c;

This query will return lists of customers assuming there is an appropriate constructor.

You should really pay attention with this approach of partially loaded entities because updating these entities could lead to accidently loosing data.

Benjamin is Software Engineer, Full Stack Developer at Pondus, an excited runner and table foosball player. Get in touch on Twitter and GitHub.

Read More