Question

I found grails criteria and want to customize sorting options.

E.g. I have domain Book and I want to make some criteria:

Book.createCriteria().list {
    //some code like ilike('name', 'book')
    ...

    order(params.sort, params.order)
}

I want to make specific sorting rule, e.g. by name.trim().

How can I do this?

Was it helpful?

Solution

Based on a solution provided here, by extending the hirbernate Order class, you can customize it to accept functions and use it with createCriteria. I wont be surprised, if there is a nicer and easier approach since this source is pretty old and also Grails is cooler than this :D

First you need a class extending Hibernate Order:

Originally by:spostelnicu

public class OrderBySqlFormula extends Order {
    private String sqlFormula;

    protected OrderBySqlFormula(String sqlFormula) {
        super(sqlFormula, true);
        this.sqlFormula = sqlFormula;
    }

    public String toString() {
        return sqlFormula;
    }

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

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


}

Then you can pass instance of this class to your createCriteria:

def ls = Domain.createCriteria().list {
       order OrderBySqlFormula.sqlFormula("TRIM(name)")
}

Note1: You can pass any formula to sqlFormula as long as the underlying database accepts it.

Note2: Using such approach might cause migration challenges.

Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top