Hibernate criteria: how to order by two columns concatenated?
I have a Person table which has two columns: first_name and last_name. The Person class has two corresponding fields: firstName and lastName. Now I'm using criteria api and trying to create an order by based on these two columns conca开发者_高级运维tenated. Is it possible? Or it can only be achieved by hql?
Here an example for the JBoss hibernate site:
from DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate
Or from the same website, for the Criteria api:
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "F%")
.addOrder( Order.asc("name") )
.addOrder( Order.desc("age") )
.setMaxResults(50)
.list();
They seem to be quite fond of cats at JBoss.
I had the same problem and criteria api orderBy method won't work with concatenated columns. I needed this to use with criteriaBuilder.construct() method. I solved this by extending Orale10gDialect class and registering custom function:
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.type.StandardBasicTypes;
public class CustomOracle10gDialect extends Oracle10gDialect {
public CustomOracle10gDialect() {
super();
// This must be used due to bug in Hibernate (orderBy won't work with concat)
registerFunction("concatwithspace", new SQLFunctionTemplate(StandardBasicTypes.STRING, "?1 || ' ' || ?2"));
}
}
And then:
Expression<String> user = cb.function("concatwithspace", String.class, criteriaRoot.get("firstname"), criteriaRoot.get("lastname"));
...
criteriaQuery.orderBy(cb.asc(user));
Of course you must also select this concatenated columns.
精彩评论