MSA
MSA

Reputation: 2482

Hibernate Criteria order by term length

I want to order my terms by lenght,which is equivalent to:

SELECT term FROM <table_name> where term  like '%now%' order by length(term ) asc;

in hibernate.

For the moment this is my criteria code:

    Criteria criteria = session.createCriteria(myClass.class);
    criteria.setProjection(Projections.distinct(Projections.property("term")));
    criteria.add(Restrictions.ilike("term", "%xyz%"));
    criteria.addOrder(Order.asc("term"));
    criteria.setMaxResults(10);
    List<String> list = criteria.list();

Cheers

Upvotes: 5

Views: 1919

Answers (2)

user4090433
user4090433

Reputation:

There is no way you can order in Criteria something like that, you need to use JPQL for that kind of order.

JPQL Order Documentation: Documentation

Upvotes: 1

Alan Hay
Alan Hay

Reputation: 23246

According to this JPAQL has a length function.

http://www.objectdb.com/java/jpa/query/jpql/string

and 10.2.5.16

http://docs.oracle.com/cd/E28613_01/apirefs.1211/e24396/ejb3_langref.html

There's some comment in 8.1.6 here about the equivalent Criteria:

http://webdev.apl.jhu.edu/~jcs/ejava-javaee/coursedocs/605-784-site/docs/content/html/jpa-query-criteria-function.html

None of the covers applying it to order by clause rather than where clause but hopefully of use.

Upvotes: 1

Related Questions