How To Customize “Hibernate Order By”

There was an issue with ordering date fields that has been stored as string type in database-side. I needed to fix the issue applying minimum changes.
So I tried to apply a type casting over string fields that contain date contents, but it wasn’t work for me.
Finely I made an override to the Hibernate Order By criteria and It works like a charm.

The following class extends Hibernate Order class overrides the behavior I needed to customize…

package com.hyperbase.core.util;

/**
 * Created by IntelliJ IDEA.
 * User: amirsedighi
 * Date: May 15, 2012
 * Time: 6:59:38 PM
 * To change this template use File | Settings | File Templates.
 */

public class CustomizedOrderBy extends Order {
    private String sqlExpression;

    protected CustomizedOrderBy(String sqlExpression) {
        super(sqlExpression, true);
        this.sqlExpression = sqlExpression;
    }


    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
        return sqlExpression;
    }

    public static Order sqlFormula(String sqlFormula) {
        return new CustomizedOrderBy(sqlFormula);
    }

    public String toString() {
        return sqlExpression;
    }

}

The way I used it also is very simple:

            Criteria criteria = hbSession.getPublishModeSession().createCriteria("User_" + table.getGeneratedID());
            if (sortBy != null){
                if (sortDir.equalsIgnoreCase("asc")){
                    if (sortBy.getType().equalsIgnoreCase("date")){
                        criteria.addOrder(CustomizedOrderBy.sqlFormula("convert( datetime, "+sortBy.getInnerName()+"  , 101) "+ sortDir));
                    } else {
                        criteria.addOrder(Order.asc(sortBy.getInnerName()));
                    }

                } else if (sortDir.equalsIgnoreCase("desc")) {
                    if (sortBy.getType().equalsIgnoreCase("date")){
                        criteria.addOrder(CustomizedOrderBy.sqlFormula("convert( datetime, "+sortBy.getInnerName()+"  , 101) "+ sortDir));
                    } else {
                        criteria.addOrder(Order.desc(sortBy.getInnerName()));
                    }

                }
            }

I like it.

This entry was posted in Java. Bookmark the permalink.

One Response to How To Customize “Hibernate Order By”

  1. Ricardo Mestre says:

    I had the same kind of issue.
    This really made my day =) Thank you

Leave a Reply