Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom order by string parameter in HQL

Tags:

hibernate

hql

I had an HQL query like this:

Query query = session.createQuery("from User as user where user.joined!=null order by user.joined desc");

How do I set a variable User property as the sort order for my query? My solution:

String order = "user.joined";
Query query = session.createQuery("from User as user where user.joined!=null order by :order desc").setString("order", order);

does not give an ordered query result.

like image 744
Cichy Avatar asked Sep 22 '11 19:09

Cichy


2 Answers

Use a criteria query.

List<User> users = session.createCriteria(User.class)
    .add(Restrictions.isNotNull("joined"))
    .addOrder(Order.desc(order))
    .list();

Or, using HQL:

Query query = session.createQuery("from User as user where user.joined!=null order by user." + order + " desc");
like image 117
Matt Ball Avatar answered Nov 10 '22 19:11

Matt Ball


In your second query, when you use this method call:

[Hibernate Query object].setString("order", order)

You are trying to bind a column name as a parameter, which is not possible.

What is a parameter (for this concern) follows the SQL parameters definition, wich is also the parameter definition used in JDBC API PreparedStatement.

To dynamically build a query (besides it's parameters) there are other solutions like the ones pointed by Matt Ball. You could also see Using a prepared statement and variable bind Order By in Java with JDBC driver.

like image 45
José Andias Avatar answered Nov 10 '22 19:11

José Andias