tags:

views:

112

answers:

3

Is there a way I can pull off the below query (order by followed by a like) using hibernate criteria api?

select * from table where first_name like 'bar%' order by first_name like 'bar%' desc
A: 

I believe your just looking for order by first_name desc...

Fried Hoeben
+1  A: 

You can't easily map this query to Criteria API because Order class only supports property names / aliases and not expressions.

You can, however, try one of the following:

  1. If the underlying database supports the expression you're trying to order by in SELECT clause, you can define a Projection with some alias (depending on expression you may have to use Projections.sqlProjection() to do so) and then order by that alias.

  2. Otherwise, you can extend Order class and overwrite its toSqlString() method to generate SQL as you see fit. Be careful that you don't make it non-portable across different databases.

P.S. To address some of the above comments, I'm pretty sure that ORDER BY expression is ANSI SQL standard (can't be 100% sure, though, seeing as how it's not publicly available). It's certainly a de-facto standard - it's supported by latest MySQL / PostgreSQL / Oracle / SQL Server versions.

ChssPly76
I do not want to extend Order class. If I go the projection way, will not the sql in projection be part of the select query?
Abhi
Certainly will. That's why I said you can only do that if your database supports such an expression as part of `SELECT` clause. If that's not the case and you don't want to extend `Order` (why?) your only option is to use native SQL query instead of `Criteria`.
ChssPly76
I was using SQL query but thought it will become more comprehensible if I do it using criteria API. But, extending Order will confuse people more than help. Also, this is only for a small task which is sort of one off. Thanks for your help.
Abhi
A: 

this can be done using the addOrder method of the criteria API:

List<Customer> result=(List<Customer>) session.createCriteria(Customer.class)
                           .add(Restrictions.like("firstName", "bar%"))
                           .addOrder(Order.desc("firstName"))
                           .list();

check here:

Hibernate Criteria Api

smeg4brains
Thanks. But this does not take the like criteria while ordering.
Abhi