Question

i have this simple MySQL query :

SELECT * from foo ORDER BY (col1+col2+col3) DESC;

the result of col1+col2+col3 is an Integer.

is there a way to make this with DetachedCriteria using hibernate for spring ?

P.S. i'm quite inexperienced with DetachedCriteria

Thanks

Was it helpful?

Solution

Yes there is a way using the formula annotation. The annotation would be placed on the Foo class. Note that the formula annotation accepts sql column names and not object property names.

@Formula("col1+col2+col3")
private int calculatedValue;

public int getCalculatedValue() {
    return calculatedValue;
}

public void setCalculatedValue(int calculatedValue) {
    this.calculatedValue = calculatedValue;
}

The detached query would look like something below.

DetachedCriteria query = DetachedCriteria.forClass(Foo.class);
query.addOrder(Order.desc("calculatedValue"));
List<Foo> results = query.getExecutableCriteria(session).setMaxResults(100).list();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top