0

I have a Entity :

class User{
    Long id;
    String group_name;
    User head;        
}

I have to get ordered users in order : order by group_name, if user is head then first (head means than head.id = id).

I make HQL Query : select u from User u order by u.group_name, case when u = head then 0 else 1; But it's not working;

In result I would like to have : (group_name : user)

  1. g1 John (head)
  2. g1 James
  3. g1 Adam
  4. g2 Brian (head)
  5. g2 Martin

How to make correct HQL query ?

idmitriev
  • 4,619
  • 4
  • 28
  • 44

2 Answers2

0

Here is HQL query:

"select u.group_name from User u, User.head head where head.id=u.id order by u.group_name"

I didn't get what exactly from User you want since there is no column name in User class so that you can include in select part.

Sushant Tambare
  • 526
  • 2
  • 9
  • Sorry, but I have a ordered list by group name – idmitriev Oct 07 '14 at 11:43
  • I your case I got just head users, but I want to get not head user as well – idmitriev Oct 07 '14 at 11:53
  • "select u.group_name from User u left join User.head head where head.id=u.id order by u.group_name" - Use this one.. it is left join which will give you both head as well as non head users as well. But then its like selecting whole User table itself. – Sushant Tambare Oct 07 '14 at 11:57
  • I want to have head user at first position !!! see example in my post. g1 John (head) Head on first position . – idmitriev Oct 07 '14 at 11:58
0

I would do this without grouping, by using a case statement to create a second attribute that you can order on to establish if someone is head of a group. For example:

select name,group_name,case when head.id is not null then 1 else 0 end as h 
from User 
order by group_name asc,h desc

As you can see, I have used a case statement to create an attribute h which takes the value 1 when someone is head of a group, or 0 otherwise. Then you can order on that descending, which will mean the head of each group is listed before the other members of the group.

Hedley
  • 1,060
  • 10
  • 24