joshua
joshua

Reputation: 4198

Adding OrderBy clause to a named query

Is it possible to add an OrderBy clause in to JPA Named query at runtime?

Upvotes: 3

Views: 3913

Answers (3)

Jack
Jack

Reputation: 1606

Even if you can't add order-by clause to your named query, you can provide a parametric orderBy. The following is a perfectly valid query:

SELECT u FROM User u ORDER BY :orderBy

And you are going to change ordering with something like:

query.setParameter("orderBy", "id");

Upvotes: -2

Jim Tough
Jim Tough

Reputation: 15210

Named queries are processed by the persistence provider when the EntityManagerFactory is created. You can't change/modify/append anything about a named query dynamically at runtime.

If you are using JPA 2.0 and you need a way to do high-performance dynamic queries at runtime, you should look into the Criteria API.

Upvotes: 2

Nayan Wadekar
Nayan Wadekar

Reputation: 11602

From Java EE 5 Documentation : "Is used to specify a named query in the Java Persistence query language, which is a static query expressed in metadata. Query names are scoped to the persistence unit".

As it says, it is static & you can't change the query at runtime. Rather use custom query or if ordering element is fixed then you can use annotation;

Field:

@OrderBy(value="nickname")
List<Person> friends;

Method:

@OrderBy("nickname ASC")
public List<Person> getFriends() {...};

Upvotes: 1

Related Questions