I want to add sorting to a HTML table populated by Hibernate. The actual sorting has to be done by a database. To feed “Order by” condition to the database Java has to match passed sort parameters to a column in a query. I’m unsure how to implement this matching.
I could pass something like “Employee.salary” but then this condition need to be checked like all parameters passed from client. This check would require getting column name from Hibernate annotations, and this is not easy I guess. Also, the column can be query-specific and not corresponding to a table field.
Another way is to use hardcoded values in a presentation layer. But this will tie presentation layer with a persistence layer, which is also not good I think.
How do you deal with server-side sorting in web applications?
If I have an
Employeeentity, then I want anEmployeeRepositorythat lets mefindEmployeesBySalary(SortType sortType, int skip, int limit)From the web service side, I want a URI like
which returns something like (as a AJAX XHR call)
or the full-blown HTML page rendered appropriate.
This conveniently allows caching of employees on the client side (which the cache size being flexible) and at the HTTP level.
Note that, column names? Irrelevant. You would have a
HiberateEmployeeRepositorythat implements theEmployeeRepositoryinterface as needed. Express this stuff as methods, and use complex parameters if you need to.You could even have two separate methods if you want, rather than an enum,
findHighestPaidEmployeesandfindLowestPaidEmployees–foo.com/employees?salary=lowest&skip=10&take=30mind you, that’s a horribly depressing URI.