Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically sorting a NamedQuery? Seam/Hibernate/JPA

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?

like image 873
Shadowman Avatar asked Nov 23 '10 14:11

Shadowman


2 Answers

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.

like image 119
Nayan Wadekar Avatar answered Sep 21 '22 17:09

Nayan Wadekar


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.

like image 3
SaSConsul Avatar answered Sep 24 '22 17:09

SaSConsul