Custom order by string parameter in HQL

I had a HQL query:

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

How to set a variable of the User property as the sort order for my request? My decision:

 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.

+4
source share
2 answers

Use query criteria .

 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"); 
+2
source

In your second request, 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 task) follows the SQL parameter definition, which is also the parameter definition used in the JDBC API PreparedStatement .

In order to dynamically build a query (in addition to its parameters), there are other solutions, similar to those indicated by Matt Ball. You can also see using the prepared statement and the bind Order By variable in Java with the JDBC driver .

+1
source

All Articles