Convert string to int in Hibernate order criterion

Despite the topic is old and may be the problem were solved, I'll post solution. Maybe it will be helpful in future for someone.

criteria.addOrder(new org.hibernate.criterion.Order("anystring", true) {
            @Override
            public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
                return "cast(id as int)";
            }
        });

If the column contains integer values, the best solution is to map it as an integer rather than a String.

If, for obscure reasons, this is not possible, you could add a integer field annotated with @Formula("cast(id) as number") in your entity and order on this field.

Tags:

Hibernate