I have some problems with Hibernate (JPA), PostgreSQL and ordering.
For example, we have two tables (mapped to entities):
- Pets (id (id), PetTypes (types_id), description (description))
- PetTypes (id (id), name (name))
type_id field is not required (constraint to pet_types table).
For example, we have 10 lines at pets table (at 1, 2 and 3 lines type_id is null). I need to order pets table by pet_types.name using HQL or JPA criteria (but i think its not supported by JPA).
Problem: values from pets table are not selecting with ordering if type_id is null. I can try to use next solutions:
- FROM Pets pets ORDER BY pets.petTypes.name ASC NULLS LAST
- FROM Pets pets ORDER BY CASE WHEN pets.petTypes IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC NULLS LAST
- FROM Pets pets ORDER BY CASE WHEN pets.petTypes.name IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC NULLS LAST
- FROM Pets pets LEFT JOIN pets.petTypes ORDER BY pets.petTypes.name ASC NULLS LAST
- FROM Pets pets ORDER BY pets.petTypes ASC NULLS LAST, pets.petTypes.names ASC
- FROM Pets pets ORDER BY CASE WHEN pets.petTypes IS NULL OR pets.petTypes.name IS NULL THEN 0 ELSE 1 END, ORDER BY pets.petTypes.name ASC
But nothing works. After selecting we have 7 instead of 10 rows. Any ideas?
I can't use UNION
statement via HQL. It's open Hibernate bug since 2005.
EDIT
Thx to Rodrigo Menezes. This solution is works:
select p from Pets p
left join p.petTypes pt
order by case when pt is null then 0 else 1 end, pt.name
CROSS JOIN
statement for Pets and PetTypes tables – Andrew Sikorsky