Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Named Query Order By parameter

Tags:

Can anyone point me to how we can pass an order by clause as a named parameter to HQL?

Example which works:

select tb from TransportBooking as tb  and TIMESTAMP(tb.bookingDate, tb.bookingTime) >= current_timestamp() order by tb.bookingDate 

Example which does not work:

select tb from TransportBooking as tb  and TIMESTAMP(tb.bookingDate, tb.bookingTime) >= current_timestamp() order by :order 
like image 387
Jet Abe Avatar asked Nov 08 '10 00:11

Jet Abe


People also ask

How do you use named queries in Hibernate?

Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code. Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries.

How do you sort data in Hibernate?

The Order class has two methods to set the sorting order: asc(String attribute) : Sorts the query by attribute in ascending order. desc(String attribute) : Sorts the query by attribute in descending order.

How do you call a named query?

You call the createNamedQuery method on the EntityManager with the name of the named query you want to execute. That gives you an instance of a Query or TypedQuery interface. You then call the setParameter method on the returned interface for each bind parameter used in your query.


1 Answers

Not supported, input parameters are only allowed in the WHERE and HAVING clauses and you cannot use parameters for the ORDER BY clause. Or if I rephrase, you can't use parameters for columns, only values. So, either:

  • Have as much named queries as possible sort orders
  • Concatenate the ordering string to the query string
  • Use criteria queries
like image 135
Pascal Thivent Avatar answered Oct 31 '22 15:10

Pascal Thivent