Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding OrderBy clause to a named query

Tags:

jpa

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

like image 919
joshua Avatar asked Dec 09 '25 08:12

joshua


2 Answers

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.

like image 88
Jim Tough Avatar answered Dec 12 '25 18:12

Jim Tough


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() {...};
like image 42
Nayan Wadekar Avatar answered Dec 12 '25 17:12

Nayan Wadekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!