Dynamic sorting of NamedQuery? Seam / Hibernate / JPA

I have several NamedQuery , and I would like to be able to sort by field for the object dynamically, without having to create a unique NamedQuery for each field that I want to sort. For example:

I have a MyObject with fields 'a', 'b', and 'c'. My basic query is " SELECT DISTINCT o FROM MyObject o ", but I would like to add an ORDER BY to my query. Ideally, I could do something like named parameters, where my query would look like this:

 SELECT DISTINCT o FROM MyObject o ORDER BY :order 

Then I have to specify the field (a, b, c) that I want to sort. Is there a way to do this using Seam / Hibernate / JPA? Is there a better strategy to solve this problem?

+7
sorting hibernate jpa seam
source share
2 answers

Named queries cannot be modified 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(); } 

Specifically its JPA.

+5
source share

See my solution in hibernate-named-query-order-by-partameter

The main idea is to save the request without the order by clause and edit it at run time.

+3
source share

All Articles