19

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 concatenated. Is it possible? Or it can only be achieved by hql?

4

2 回答 2

27

这是JBoss hibernate 站点的示例:

from DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate

或者来自同一个网站,对于Criteria api

List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "F%")
.addOrder( Order.asc("name") )
.addOrder( Order.desc("age") )
.setMaxResults(50)
.list();

他们似乎很喜欢 JBoss 的猫。

于 2011-07-19T21:00:29.347 回答
0

我遇到了同样的问题,并且标准 api orderBy 方法不适用于连接列。我需要将它与 criteriaBuilder.construct() 方法一起使用。我通过扩展 Orale10gDialect 类和注册自定义函数解决了这个问题:

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"));
    }

}

接着:

Expression<String> user = cb.function("concatwithspace", String.class, criteriaRoot.get("firstname"), criteriaRoot.get("lastname")); 

...

criteriaQuery.orderBy(cb.asc(user));

当然,您还必须选择此串联列。

于 2017-11-07T09:59:33.863 回答