views:

50

answers:

2

I have this class mapped

@Entity
@Table(name = "USERS")
public class User {
 private long id;
 private String userName;
}

and I make a query:

Query query = session.createQuery("select id, userName, count(userName) from User order by count(userName) desc");
            return query.list();

How can I access the values returned by the query?

I mean, how should I treat the query.list()? As a User or what?

+3  A: 

To strictly answer your question, queries that specify a property of a class in the select clause (and optionally call aggregate functions) return "scalar" results i.e. a Object[] (or a List<Object[]>). See 10.4.1.3. Scalar results.

But your current query doesn't work. You'll need something like this:

select u.userName, count(u.userName) 
from User2633514 u 
group by u.userName 
order by count(u.userName) desc
Pascal Thivent
+1  A: 

I'm not sure how Hibernate handles aggregates and counts, but I'm not sure if your query is going to work at all. You're trying to select a aggregate (i.e. the "count(userName)"), but you don't have a "group by" clause for userName.

If the query does in fact work, and Hibernate can figure out what to do with it, the results you get back will most likely be a raw Object[], because Hibernate will not be able to map your "count(userName)" data into any field on your mapped objects.

Overall, when you get into using aggregates in queries, Hibernate can get a little more tricky, since you're no longer mapping tables/columns directly into classes/fields. It might be a good idea to read up more on how to do aggregates in Hibernate, from their documentation.

Andy White