I have several NamedQuery
's defined, and I'd like to be able to sort on a field for an entity dynamically, without having to create unique NamedQuery
's for each field I want to sort on. For example:
I have an entity called MyObject, with fields 'a', 'b', and 'c'. My base query is "SELECT DISTINCT o FROM MyObject o
", but I'd like to be able to add an ORDER BY
clause to my query. Ideally, I'd be able to do something like named parameters, where my query would look like:
SELECT DISTINCT o FROM MyObject o ORDER BY :order
I would then specify the field (a, b, c) that I want to sort on. Is there any way to accomplish this using Seam/Hibernate/JPA? Is there a better strategy for tackling this?
Named queries cannot be changed at run-time.
//----- Edited-part
public void getOrders(String orderByElement){
String query = "SELECT DISTINCT o FROM MyObject o ORDER BY " + orderByElement;
entityManager.createQuery(query).getResultList();
}
Its JPA specific.
See my solution in hibernate-named-query-order-by-partameter
Basic idea is to store the query without the 'order by clause and edit it on at run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With