Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int in Hibernate order criterion

Tags:

hibernate

Basically, my question is the same as this one, but for Java's (JBoss) Hibernate: How can we order a column as int using hibernate criteria API?

I want to create an order restriction with a cast to int from a string column. Something like

criteria.addOrder(Order.asc("cast(id as int)"));

The exception is "Could not resolve property: cast(id as int) of [Class]". I've tried both cast( as ) and convert(,) with int and integer.

like image 980
spnbldk Avatar asked Jul 18 '12 16:07

spnbldk


1 Answers

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)";
            }
        });
like image 123
yorlin Avatar answered Sep 24 '22 23:09

yorlin