torourke
torourke

Reputation: 1979

Sorting a list of JPQL Entities

I've searched long and hard for an answer, but I haven't had any luck so far. I'm trying to retrieve and sort a list of objects via a JPQL query, but since the query itself uses a lot of joins between different tables, it's really difficult.

Basically, we have an entity "Person" with the fields

String name
List<Telephone> phones
List<Email> emails
List<Address> addresses

"Telephone", "Email", and "Address" are all separate Entities, each containing its own data, like a String field "number" or something similar (Address.street, Address.state). So all four of these objects are tables in the database.

I want the user to be able to sort a list of Persons by any particular data. Right now, I want to sort by any one of the following: the Person's name, the first email address in the emails list, by the street or state of the person's first address, and so on. So if a list of Persons is of the following:

Name     Phone Number        Street          State
Mack     555-1234            1 Main Street   WA
Andy     222-9999            2 Other Way     RI
Wendy    222-3333            3 Wrong Way     UT

and I want the table to be sorted by State, the list should be:

Name     Phone Number        Street          State
Andy     222-9999            2 Other Way     RI
Wendy    222-3333            3 Wrong Way     UT
Mack     555-1234            1 Main Street   WA

I want this to be done using a JPQL query so a list is already filtered and sorted when it's given to the web server to optimize performance. I must also add that I am implementing a search feature that searches all these "columns" for a particular term.

Long story short, how do I write a JPQL query such that a can obtain a list of Person objects that have been sorted for one of these columns? My implementation of "SELECT DISTINCT":

SELECT DISTINCT x FROM Person x, IN(x.phones) phones ORDER BY phones.number

doesn't work since the result table requires to have the column being sorted (which is invalid because it causes the list to not qualify as a list of Person objects), and I can't seem to use nested SELECT statements to generate the result set and then pull a list of Person objects from that. Is there any easy way to do this?

Upvotes: 4

Views: 2043

Answers (1)

OmegaZiv
OmegaZiv

Reputation: 266

I am sorry but I must disagree. In JPQL you can (!) sort the result set without including the sorted column in the result.

See any Hibernate example (as a promonent JPQL implementation).

Please let me know if I miss understood


SELECT DISTINCT p FROM Person p 
                   JOIN p.addressList adr 
                   JOIN p.emailList eml 
                   JOIN p.phoneList phn
ORDER BY p.name, eml.emailAddress, phn.phoneNumber

Upvotes: 4

Related Questions